"""
Router Notifiche Multi-canale (Fase 2).

Endpoint:
  POST   /notifications/channels                     → crea canale
  GET    /notifications/channels                     → lista canali
  GET    /notifications/channels/{id}                → dettaglio canale
  PATCH  /notifications/channels/{id}                → aggiorna canale
  DELETE /notifications/channels/{id}                → elimina canale
  POST   /notifications/channels/{id}/test           → test canale
  POST   /notifications/rules                        → crea regola
  GET    /notifications/rules                        → lista regole
  GET    /notifications/rules/{id}                   → dettaglio regola
  PATCH  /notifications/rules/{id}                   → aggiorna regola
  DELETE /notifications/rules/{id}                   → elimina regola
  GET    /notifications/logs                         → log invii
"""

import uuid

from fastapi import APIRouter, Query

from app.dependencies import AdminUser, DB
from app.schemas.notification import (
    ChannelTestResult,
    NotificationChannelCreate,
    NotificationChannelListResponse,
    NotificationChannelResponse,
    NotificationChannelUpdate,
    NotificationLogListResponse,
    NotificationLogResponse,
    NotificationRuleCreate,
    NotificationRuleListResponse,
    NotificationRuleResponse,
    NotificationRuleUpdate,
)
from app.services.notification_service import NotificationService

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


# ─── Channels ─────────────────────────────────────────────────────────────────

@router.post(
    "/channels",
    response_model=NotificationChannelResponse,
    status_code=201,
    summary="Crea un canale di notifica",
)
async def create_channel(
    body: NotificationChannelCreate,
    current_user: AdminUser,
    db: DB,
) -> NotificationChannelResponse:
    service = NotificationService(db)
    channel = await service.create_channel(current_user.tenant_id, body, current_user.id)
    return NotificationChannelResponse.model_validate(channel)


@router.get(
    "/channels",
    response_model=NotificationChannelListResponse,
    summary="Lista canali di notifica",
)
async def list_channels(
    current_user: AdminUser,
    db: DB,
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
) -> NotificationChannelListResponse:
    service = NotificationService(db)
    items, total = await service.list_channels(current_user.tenant_id, page, page_size)
    return NotificationChannelListResponse(
        items=[NotificationChannelResponse.model_validate(c) for c in items],
        total=total,
        page=page,
        page_size=page_size,
    )


@router.get(
    "/channels/{channel_id}",
    response_model=NotificationChannelResponse,
    summary="Dettaglio canale",
)
async def get_channel(
    channel_id: uuid.UUID,
    current_user: AdminUser,
    db: DB,
) -> NotificationChannelResponse:
    service = NotificationService(db)
    channel = await service.get_channel(channel_id, current_user.tenant_id)
    return NotificationChannelResponse.model_validate(channel)


@router.patch(
    "/channels/{channel_id}",
    response_model=NotificationChannelResponse,
    summary="Aggiorna canale",
)
async def update_channel(
    channel_id: uuid.UUID,
    body: NotificationChannelUpdate,
    current_user: AdminUser,
    db: DB,
) -> NotificationChannelResponse:
    service = NotificationService(db)
    channel = await service.update_channel(channel_id, current_user.tenant_id, body)
    return NotificationChannelResponse.model_validate(channel)


@router.delete(
    "/channels/{channel_id}",
    status_code=204,
    summary="Elimina canale",
)
async def delete_channel(
    channel_id: uuid.UUID,
    current_user: AdminUser,
    db: DB,
) -> None:
    service = NotificationService(db)
    await service.delete_channel(channel_id, current_user.tenant_id)


@router.post(
    "/channels/{channel_id}/test",
    response_model=ChannelTestResult,
    summary="Test canale di notifica",
    description="Invia un messaggio di test al canale per verificarne la configurazione.",
)
async def test_channel(
    channel_id: uuid.UUID,
    current_user: AdminUser,
    db: DB,
) -> ChannelTestResult:
    service = NotificationService(db)
    return await service.test_channel(channel_id, current_user.tenant_id)


# ─── Rules ────────────────────────────────────────────────────────────────────

@router.post(
    "/rules",
    response_model=NotificationRuleResponse,
    status_code=201,
    summary="Crea una regola di notifica",
)
async def create_rule(
    body: NotificationRuleCreate,
    current_user: AdminUser,
    db: DB,
) -> NotificationRuleResponse:
    service = NotificationService(db)
    rule = await service.create_rule(current_user.tenant_id, body)
    return NotificationRuleResponse.model_validate(rule)


@router.get(
    "/rules",
    response_model=NotificationRuleListResponse,
    summary="Lista regole di notifica",
)
async def list_rules(
    current_user: AdminUser,
    db: DB,
    channel_id: uuid.UUID | None = Query(None),
    page: int = Query(1, ge=1),
    page_size: int = Query(50, ge=1, le=200),
) -> NotificationRuleListResponse:
    service = NotificationService(db)
    items, total = await service.list_rules(
        current_user.tenant_id, channel_id, page, page_size
    )
    return NotificationRuleListResponse(
        items=[NotificationRuleResponse.model_validate(r) for r in items],
        total=total,
    )


@router.get(
    "/rules/{rule_id}",
    response_model=NotificationRuleResponse,
    summary="Dettaglio regola",
)
async def get_rule(
    rule_id: uuid.UUID,
    current_user: AdminUser,
    db: DB,
) -> NotificationRuleResponse:
    service = NotificationService(db)
    rule = await service.get_rule(rule_id, current_user.tenant_id)
    return NotificationRuleResponse.model_validate(rule)


@router.patch(
    "/rules/{rule_id}",
    response_model=NotificationRuleResponse,
    summary="Aggiorna regola",
)
async def update_rule(
    rule_id: uuid.UUID,
    body: NotificationRuleUpdate,
    current_user: AdminUser,
    db: DB,
) -> NotificationRuleResponse:
    service = NotificationService(db)
    rule = await service.update_rule(rule_id, current_user.tenant_id, body)
    return NotificationRuleResponse.model_validate(rule)


@router.delete(
    "/rules/{rule_id}",
    status_code=204,
    summary="Elimina regola",
)
async def delete_rule(
    rule_id: uuid.UUID,
    current_user: AdminUser,
    db: DB,
) -> None:
    service = NotificationService(db)
    await service.delete_rule(rule_id, current_user.tenant_id)


# ─── Logs ─────────────────────────────────────────────────────────────────────

@router.get(
    "/logs",
    response_model=NotificationLogListResponse,
    summary="Log notifiche",
)
async def list_logs(
    current_user: AdminUser,
    db: DB,
    channel_id: uuid.UUID | None = Query(None),
    page: int = Query(1, ge=1),
    page_size: int = Query(50, ge=1, le=200),
) -> NotificationLogListResponse:
    service = NotificationService(db)
    items, total = await service.list_logs(
        current_user.tenant_id, channel_id, page, page_size
    )
    return NotificationLogListResponse(
        items=[NotificationLogResponse.model_validate(l) for l in items],
        total=total,
        page=page,
        page_size=page_size,
    )
