"""Shared authorization helpers for patient-owned resources."""
from typing import Optional, Tuple

from flask import Response, g, jsonify

from app.models.user import User
from app.repositories import find_user_by_id
from app.routes.auth import can_read_user_data


def ensure_can_access_patient_data(patient_id: str) -> Tuple[Optional[User], Optional[Tuple[Response, int]]]:
    """Return patient user and optional error response if requester cannot access data."""
    patient = find_user_by_id(patient_id)
    if not patient:
        return None, (jsonify({'error': 'PatientNotFound'}), 404)

    shared_with = (str(user_id) for user_id in (patient.sharingInfo or []))
    if not can_read_user_data(str(patient.id), shared_with):
        return patient, (jsonify({'error': 'Forbidden', 'detail': 'Not allowed for this user'}), 403)

    return patient, None


def ensure_can_create_for_patient(patient_id: str) -> Optional[Tuple[Response, int]]:
    """Allow create when requester is admin, patient themselves, or a practitioner in the patient's sharingInfo."""
    auth_user = g.get('auth_user') or {}
    requester_id = str(auth_user.get('sub', ''))
    requester_roles = set(auth_user.get('roles', []))

    if not patient_id:
        return jsonify({'error': 'MissingField', 'field': 'patientId'}), 400

    patient = find_user_by_id(patient_id)
    if not patient:
        return jsonify({'error': 'PatientNotFound'}), 404

    is_admin = 'admin' in requester_roles
    if is_admin or requester_id == str(patient_id):
        return None

    is_practitioner = 'practitioner' in requester_roles
    shared_ids = {str(uid) for uid in (patient.sharingInfo or [])}
    if is_practitioner and requester_id in shared_ids:
        return None

    return jsonify({'error': 'Forbidden', 'detail': 'Not allowed to create records for this patient'}), 403
