from uuid import UUID

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

from app.core.database import get_db
from app.core.security import require_platform_admin
from app.schemas.user import MembershipCreate, MembershipRead, UserCreate, UserRead
from app.services.user_service import UserService

router = APIRouter(tags=["users"])


@router.get("/users", response_model=list[UserRead])
async def list_users(
    offset: int = Query(default=0, ge=0),
    limit: int = Query(default=50, ge=1, le=100),
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
) -> list[UserRead]:
    users = await UserService(db).list_users(offset=offset, limit=limit)
    return [UserRead.model_validate(user) for user in users]


@router.post("/users", response_model=UserRead, status_code=status.HTTP_201_CREATED)
async def register_user(
    payload: UserCreate,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
) -> UserRead:
    user = await UserService(db).register(payload)
    return UserRead.model_validate(user)


@router.get("/users/{user_id}", response_model=UserRead)
async def get_user(
    user_id: UUID,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
) -> UserRead:
    user = await UserService(db).get(user_id)
    return UserRead.model_validate(user)


@router.post(
    "/tenants/{tenant_id}/members",
    response_model=MembershipRead,
    status_code=status.HTTP_201_CREATED,
)
async def add_tenant_member(
    tenant_id: UUID,
    payload: MembershipCreate,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
    authorization: str | None = Header(default=None),
) -> MembershipRead:
    membership = await UserService(db).add_member(
        tenant_id, payload, authorization=authorization
    )
    return MembershipRead.model_validate(membership)


@router.get("/tenants/{tenant_id}/members", response_model=list[MembershipRead])
async def list_tenant_members(
    tenant_id: UUID,
    db: AsyncSession = Depends(get_db),
    _user=Depends(require_platform_admin),
) -> list[MembershipRead]:
    rows = await UserService(db).list_members(tenant_id)
    return [MembershipRead.model_validate(m) for m in rows]
