"""
Router permessi granulari casella (Fase 1-A).

Endpoint:
  POST   /api/v1/permissions/mailboxes/{mailbox_id}/users/{user_id}  → assegna permesso
  DELETE /api/v1/permissions/mailboxes/{mailbox_id}/users/{user_id}  → revoca permesso
  GET    /api/v1/permissions/mailboxes/{mailbox_id}/users             → utenti con accesso
  GET    /api/v1/permissions/users/{user_id}/mailboxes                → caselle accessibili
"""

import uuid

from fastapi import APIRouter

from app.dependencies import AdminUser, CurrentUser, DB
from app.schemas.permission import (
    MailboxUserPermissionResponse,
    PermissionGrantRequest,
    PermissionResponse,
    UserMailboxPermissionResponse,
)
from app.services.permission_service import PermissionService

router = APIRouter(prefix="/permissions", tags=["Permessi casella"])


@router.post(
    "/mailboxes/{mailbox_id}/users/{user_id}",
    response_model=PermissionResponse,
    status_code=201,
    summary="Assegna permesso utente su casella",
    description="Crea o aggiorna i permessi di un utente su una specifica casella PEC.",
)
async def grant_permission(
    mailbox_id: uuid.UUID,
    user_id: uuid.UUID,
    body: PermissionGrantRequest,
    current_user: AdminUser,
    db: DB,
) -> PermissionResponse:
    service = PermissionService(db)
    perm = await service.grant_permission(
        tenant_id=current_user.tenant_id,
        mailbox_id=mailbox_id,
        user_id=user_id,
        data=body,
        granted_by=current_user,
    )
    return PermissionResponse.model_validate(perm)


@router.delete(
    "/mailboxes/{mailbox_id}/users/{user_id}",
    status_code=204,
    summary="Revoca permesso utente su casella",
)
async def revoke_permission(
    mailbox_id: uuid.UUID,
    user_id: uuid.UUID,
    current_user: AdminUser,
    db: DB,
) -> None:
    service = PermissionService(db)
    await service.revoke_permission(
        mailbox_id=mailbox_id,
        user_id=user_id,
        revoked_by=current_user,
    )


@router.get(
    "/mailboxes/{mailbox_id}/users",
    response_model=list[MailboxUserPermissionResponse],
    summary="Utenti con accesso a una casella",
)
async def list_mailbox_users(
    mailbox_id: uuid.UUID,
    current_user: AdminUser,
    db: DB,
) -> list[MailboxUserPermissionResponse]:
    service = PermissionService(db)
    rows = await service.list_mailbox_users(mailbox_id, current_user.tenant_id)
    return [MailboxUserPermissionResponse(**row) for row in rows]


@router.get(
    "/users/{user_id}/mailboxes",
    response_model=list[UserMailboxPermissionResponse],
    summary="Caselle accessibili a un utente",
)
async def list_user_mailboxes(
    user_id: uuid.UUID,
    current_user: AdminUser,
    db: DB,
) -> list[UserMailboxPermissionResponse]:
    service = PermissionService(db)
    rows = await service.list_user_mailboxes(user_id, current_user.tenant_id)
    return [UserMailboxPermissionResponse(**row) for row in rows]


@router.get(
    "/my/mailboxes",
    response_model=list[UserMailboxPermissionResponse],
    summary="Caselle accessibili all'utente corrente",
)
async def my_mailboxes(
    current_user: CurrentUser,
    db: DB,
) -> list[UserMailboxPermissionResponse]:
    service = PermissionService(db)
    rows = await service.list_user_mailboxes(current_user.id, current_user.tenant_id)
    return [UserMailboxPermissionResponse(**row) for row in rows]
