"""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
from app.schemas.tenant import AdminTenantCreate, TenantRead, TenantUpdate
from app.services.tenant_service import TenantService
from shared.pagination import Page, PaginationParams
from shared.security import CurrentUser

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


@router.post("", response_model=TenantRead, status_code=status.HTTP_201_CREATED)
async def create_tenant(
    payload: AdminTenantCreate,
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_authenticated),
) -> TenantRead:
    tenant = await TenantService(db).create_for_user(user, 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: CurrentUser = Depends(require_authenticated),
) -> Page[TenantRead]:
    items, total = await TenantService(db).list_for_user(
        user, 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: CurrentUser = Depends(require_authenticated),
) -> TenantRead:
    svc = TenantService(db)
    tenant = await svc.get(tenant_id)
    svc.ensure_access(tenant, user)
    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: CurrentUser = Depends(require_authenticated),
) -> TenantRead:
    tenant = await TenantService(db).update(tenant_id, payload, user=user)
    return TenantRead.model_validate(tenant)
