"""APIهای مدیریت Tenant."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, status
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_pagination
from app.core.security import require_authenticated, require_platform_admin, require_tenant_admin
from app.schemas.tenant import TenantCreate, TenantRead, TenantUpdate
from app.services.tenant_service import TenantService
from shared.pagination import Page, PaginationParams

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


@router.post("", response_model=TenantRead, status_code=status.HTTP_201_CREATED)
async def create_tenant(
    payload: TenantCreate,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
) -> TenantRead:
    tenant = await TenantService(db).create(payload)
    return TenantRead.model_validate(tenant)


@router.get("", response_model=Page[TenantRead])
async def list_tenants(
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_authenticated),
) -> Page[TenantRead]:
    items, total = await TenantService(db).list(
        offset=pagination.offset, limit=pagination.limit
    )
    return Page.create(
        [TenantRead.model_validate(t) for t in items], total, pagination
    )


@router.get("/{tenant_id}", response_model=TenantRead)
async def get_tenant(
    tenant_id: UUID,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_authenticated),
) -> TenantRead:
    tenant = await TenantService(db).get(tenant_id)
    return TenantRead.model_validate(tenant)


@router.patch("/{tenant_id}", response_model=TenantRead)
async def update_tenant(
    tenant_id: UUID,
    payload: TenantUpdate,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_tenant_admin),
) -> TenantRead:
    tenant = await TenantService(db).update(tenant_id, payload)
    return TenantRead.model_validate(tenant)


@router.post("/{tenant_id}/suspend", response_model=TenantRead)
async def suspend_tenant(
    tenant_id: UUID,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
) -> TenantRead:
    tenant = await TenantService(db).suspend(tenant_id)
    return TenantRead.model_validate(tenant)


@router.post("/{tenant_id}/activate", response_model=TenantRead)
async def activate_tenant(
    tenant_id: UUID,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
) -> TenantRead:
    tenant = await TenantService(db).activate(tenant_id)
    return TenantRead.model_validate(tenant)
