from __future__ import annotations

from fastapi import HTTPException

from app.services.notifications import resolve_client_id
from app.store import Invoice, store


def authorize_upload_client(*, platform: str, email: str, requested_client_id: str | None) -> str:
    """Resolve and authorize which client a document may be uploaded for."""
    platform_n = platform.strip().lower()
    if platform_n == "client":
        client_id = resolve_client_id(platform_n, email, requested_client_id)
        if not client_id:
            raise HTTPException(status_code=403, detail="Your account is not linked to a client workspace")
        return client_id

    if platform_n == "firm":
        if not requested_client_id:
            raise HTTPException(status_code=400, detail="Please select a client")
        if not any(c.id == requested_client_id for c in store.snapshot().clients):
            raise HTTPException(status_code=404, detail="Client not found")
        return requested_client_id

    raise HTTPException(status_code=400, detail="Invalid platform")


def authorize_document_read(*, platform: str, email: str, invoice: Invoice) -> None:
    """Ensure the caller may read the given document."""
    platform_n = platform.strip().lower()
    if platform_n == "client":
        client_id = resolve_client_id(platform_n, email, invoice.clientId)
        if not client_id or invoice.clientId != client_id:
            raise HTTPException(status_code=403, detail="You do not have access to this document")
        return

    if platform_n == "firm":
        return

    raise HTTPException(status_code=400, detail="Invalid platform")
