from __future__ import annotations

from fastapi import APIRouter, HTTPException, Query
from pydantic import BaseModel, EmailStr, Field

from app.services import notifications as notif_service

router = APIRouter(prefix="/notifications", tags=["notifications"])


class IdentityParams(BaseModel):
    platform: str = Field(pattern="^(firm|client)$")
    email: EmailStr
    client_id: str | None = None


class MarkReadRequest(BaseModel):
    platform: str = Field(pattern="^(firm|client)$")
    email: EmailStr
    client_id: str | None = None


class MarkAllReadRequest(BaseModel):
    platform: str = Field(pattern="^(firm|client)$")
    email: EmailStr
    client_id: str | None = None


@router.get("", response_model=notif_service.NotificationListOut)
def list_notifications(
    platform: str = Query(pattern="^(firm|client)$"),
    email: EmailStr = Query(...),
    client_id: str | None = None,
    unread_only: bool = False,
    limit: int = Query(50, ge=1, le=100),
    offset: int = Query(0, ge=0),
):
    return notif_service.list_notifications(
        platform=platform,
        email=str(email).lower(),
        client_id=client_id,
        unread_only=unread_only,
        limit=limit,
        offset=offset,
    )


@router.get("/unread-count")
def get_unread_count(
    platform: str = Query(pattern="^(firm|client)$"),
    email: EmailStr = Query(...),
    client_id: str | None = None,
) -> dict[str, int]:
    count = notif_service.unread_count(
        platform=platform,
        email=str(email).lower(),
        client_id=client_id,
    )
    return {"unread_count": count}


@router.post("/{notification_id}/read", response_model=notif_service.NotificationOut)
def mark_notification_read(notification_id: int, payload: MarkReadRequest):
    item = notif_service.mark_read(
        platform=payload.platform,
        email=str(payload.email).lower(),
        notification_id=notification_id,
        client_id=payload.client_id,
    )
    if not item:
        raise HTTPException(status_code=404, detail="Notification not found")
    return item


@router.post("/read-all")
def mark_all_notifications_read(payload: MarkAllReadRequest) -> dict[str, int | bool]:
    updated = notif_service.mark_all_read(
        platform=payload.platform,
        email=str(payload.email).lower(),
        client_id=payload.client_id,
    )
    return {"ok": True, "updated": updated}
