"""CRM access-policy predicates shared by routes (no SQL here; reads live in modules.core.*_queries).

Policy (approved S1): master sees everything; any other level (agent, legacy 'admin') only its own offers and its own
private notes. The legacy 'admin' level gains nothing here.
"""
from flask import current_app, jsonify, session

from modules.core.offer_queries import get_offer_owner, list_offer_ids_of_agent


def is_master():
    return session.get('access_level') == 'master'


def offer_access_denied(offer_id):
    """None when the session may access this domestic offer, else a JSON error response (404 missing, 403 foreign)."""
    if is_master():
        return None
    user_id = session.get('user_id')
    try:
        exists, owner = get_offer_owner(offer_id)
    except Exception as exc:
        current_app.logger.warning("Nie udalo sie sprawdzic uprawnien do oferty %s: %s", offer_id, exc)
        return jsonify({'error': 'Nie udało się sprawdzić uprawnień do oferty.'}), 500
    if not exists:
        return jsonify({'error': 'Oferta nie istnieje.'}), 404
    if user_id is None or owner is None or str(owner).strip() != str(user_id).strip():
        return jsonify({'error': 'Brak uprawnień do tej oferty.'}), 403
    return None


def visible_offer_ids():
    """None for master (no restriction); otherwise the set of own offer ids as strings (empty on lookup failure)."""
    if is_master():
        return None
    user_id = session.get('user_id')
    if user_id is None:
        return set()
    try:
        return list_offer_ids_of_agent(user_id)
    except Exception as exc:
        current_app.logger.warning("Nie udalo sie pobrac ofert uzytkownika %s: %s", user_id, exc)
        return set()


def note_visible_to(note, user_id):
    """Same rule as the notes list: public notes for everyone, private notes only for their author."""
    return (not note.get('private')) or note.get('author_id') == user_id
