"""
Router regole di smistamento automatico (Feature 2).

Endpoint:
  GET    /routing-rules            – lista regole del tenant
  POST   /routing-rules            – crea regola (admin)
  GET    /routing-rules/{id}       – dettaglio regola
  PUT    /routing-rules/{id}       – aggiorna regola (admin)
  DELETE /routing-rules/{id}       – elimina regola (admin)
  POST   /routing-rules/{id}/toggle – abilita/disabilita regola (admin)
"""

import uuid

from fastapi import APIRouter, status

from app.dependencies import AdminUser, CurrentUser, DB
from app.schemas.routing_rule import (
    RoutingRuleCreate,
    RoutingRuleListResponse,
    RoutingRuleResponse,
    RoutingRuleUpdate,
)
from app.services.routing_rule_service import RoutingRuleService

router = APIRouter(tags=["Routing Rules"])


@router.get("/routing-rules", response_model=RoutingRuleListResponse)
async def list_rules(
    current_user: CurrentUser,
    db: DB,
) -> RoutingRuleListResponse:
    """Elenca le regole di smistamento del tenant."""
    svc = RoutingRuleService(db)
    items, total = await svc.list_rules(current_user.tenant_id)
    return RoutingRuleListResponse(
        items=[RoutingRuleResponse.model_validate(r) for r in items],
        total=total,
    )


@router.post("/routing-rules", response_model=RoutingRuleResponse, status_code=status.HTTP_201_CREATED)
async def create_rule(
    data: RoutingRuleCreate,
    current_user: AdminUser,
    db: DB,
) -> RoutingRuleResponse:
    """Crea una nuova regola di smistamento (solo admin)."""
    svc = RoutingRuleService(db)
    rule = await svc.create_rule(current_user.tenant_id, data, created_by=current_user.id)
    return RoutingRuleResponse.model_validate(rule)


@router.get("/routing-rules/{rule_id}", response_model=RoutingRuleResponse)
async def get_rule(
    rule_id: uuid.UUID,
    current_user: CurrentUser,
    db: DB,
) -> RoutingRuleResponse:
    """Restituisce il dettaglio di una regola."""
    svc = RoutingRuleService(db)
    rule = await svc.get_rule(current_user.tenant_id, rule_id)
    return RoutingRuleResponse.model_validate(rule)


@router.put("/routing-rules/{rule_id}", response_model=RoutingRuleResponse)
async def update_rule(
    rule_id: uuid.UUID,
    data: RoutingRuleUpdate,
    current_user: AdminUser,
    db: DB,
) -> RoutingRuleResponse:
    """Aggiorna una regola di smistamento (solo admin)."""
    svc = RoutingRuleService(db)
    rule = await svc.update_rule(current_user.tenant_id, rule_id, data)
    return RoutingRuleResponse.model_validate(rule)


@router.delete("/routing-rules/{rule_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_rule(
    rule_id: uuid.UUID,
    current_user: AdminUser,
    db: DB,
) -> None:
    """Elimina una regola di smistamento (solo admin)."""
    svc = RoutingRuleService(db)
    await svc.delete_rule(current_user.tenant_id, rule_id)


@router.post("/routing-rules/{rule_id}/toggle", response_model=RoutingRuleResponse)
async def toggle_rule(
    rule_id: uuid.UUID,
    current_user: AdminUser,
    db: DB,
) -> RoutingRuleResponse:
    """Abilita o disabilita una regola di smistamento (admin)."""
    svc = RoutingRuleService(db)
    rule = await svc.get_rule(current_user.tenant_id, rule_id)
    from app.schemas.routing_rule import RoutingRuleUpdate
    updated = await svc.update_rule(
        current_user.tenant_id,
        rule_id,
        RoutingRuleUpdate(is_active=not rule.is_active),
    )
    return RoutingRuleResponse.model_validate(updated)
