from fastapi import APIRouter, Depends, HTTPException, status

from app.api.deps import require_session, require_super_admin
from app.services.tenant_store import (
    BootstrapSuperAdminPayload,
    LoginPayload,
    RegisterTenantPayload,
    SessionIdentity,
    TenantStaffUserCreatePayload,
    TenantStaffUserUpdatePayload,
    UpdatePasswordPayload,
    get_tenant_store,
)


router = APIRouter()


@router.get("/status")
def auth_status() -> dict[str, object]:
    return get_tenant_store().status()


@router.post("/register")
def register_tenant(payload: RegisterTenantPayload) -> dict[str, object]:
    raise HTTPException(
        status_code=status.HTTP_403_FORBIDDEN,
        detail="La registrazione pubblica e disabilitata. Usa il pannello admin del super user.",
    )


@router.post("/bootstrap-super-admin")
def bootstrap_super_admin(payload: BootstrapSuperAdminPayload) -> dict[str, object]:
    try:
        session = get_tenant_store().bootstrap_super_admin(payload)
    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(session)


@router.post("/login")
def login(payload: LoginPayload) -> dict[str, object]:
    try:
        session = get_tenant_store().login(payload)
    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(session)


@router.get("/me")
def auth_me(session: SessionIdentity = Depends(require_session)) -> dict[str, object]:
    response = get_tenant_store().build_auth_response(session)
    response["authenticated"] = True
    return response


@router.put("/me/password")
def update_current_user_password(
    payload: UpdatePasswordPayload,
    session: SessionIdentity = Depends(require_session),
) -> dict[str, object]:
    try:
        get_tenant_store().update_current_user_password(session, payload)
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc

    return {"success": True}


@router.put("/super-admin/password")
def update_super_admin_password(
    payload: UpdatePasswordPayload,
    session: SessionIdentity = Depends(require_super_admin),
) -> dict[str, object]:
    try:
        get_tenant_store().update_super_admin_password(session, payload)
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc

    return {"success": True}


@router.post("/logout")
def logout(session: SessionIdentity = Depends(require_session)) -> dict[str, object]:
    get_tenant_store().logout(session.token)
    return {"success": True}


@router.get("/tenant-users")
def list_tenant_users(session: SessionIdentity = Depends(require_session)) -> dict[str, object]:
    try:
        users = get_tenant_store().list_tenant_users(session)
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(exc)) from exc

    return {"users": users}


@router.post("/tenant-users")
def create_tenant_user(
    payload: TenantStaffUserCreatePayload,
    session: SessionIdentity = Depends(require_session),
) -> dict[str, object]:
    try:
        user = get_tenant_store().create_tenant_staff_user(session, payload)
    except ValueError as exc:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc

    return {"user": user}


@router.put("/tenant-users/{user_id}")
def update_tenant_user(
    user_id: str,
    payload: TenantStaffUserUpdatePayload,
    session: SessionIdentity = Depends(require_session),
) -> dict[str, object]:
    try:
        user = get_tenant_store().update_tenant_staff_user(session, user_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 {"user": user}


@router.delete("/tenant-users/{user_id}")
def delete_tenant_user(user_id: str, session: SessionIdentity = Depends(require_session)) -> dict[str, object]:
    try:
        get_tenant_store().delete_tenant_staff_user(session, user_id)
    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}
