from fastapi import APIRouter, Depends, HTTPException, status

from app.api.deps import require_super_admin
from app.services.tenant_store import (
    AdminCreateTenantPayload,
    AdminUpdateTenantAdminPayload,
    SessionIdentity,
    get_tenant_store,
)


router = APIRouter()


@router.get("/overview")
def admin_overview(_session: SessionIdentity = Depends(require_super_admin)) -> dict[str, object]:
    return get_tenant_store().get_admin_overview()


@router.post("/tenants")
def create_tenant(
    payload: AdminCreateTenantPayload,
    _session: SessionIdentity = Depends(require_super_admin),
) -> dict[str, object]:
    try:
        tenant = get_tenant_store().create_tenant_as_super_admin(payload)
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc

    return {"success": True, "tenant": tenant}


@router.put("/tenants/{tenant_id}")
def update_tenant(
    tenant_id: str,
    payload: AdminUpdateTenantAdminPayload,
    _session: SessionIdentity = Depends(require_super_admin),
) -> dict[str, object]:
    try:
        tenant = get_tenant_store().update_tenant_admin(tenant_id, payload)
    except KeyError as exc:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc

    return {"success": True, "tenant": tenant}


@router.post("/tenants/{tenant_id}/impersonate")
def impersonate_tenant(
    tenant_id: str,
    session: SessionIdentity = Depends(require_super_admin),
) -> dict[str, object]:
    try:
        impersonated_session = get_tenant_store().impersonate_tenant(session, tenant_id)
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc

    return get_tenant_store().build_auth_response(impersonated_session)
