"""Tenant management routes."""

from __future__ import annotations

import uuid

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

from app.core.db import get_db
from app.deps import require_permission
from app.schemas.tenant import TenantCreate, TenantUserAssign
from app.services.tenant_service import tenant_service

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


@router.get("")
async def list_tenants(
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("tenants:read")),
):
    """List tenants for the current user."""
    user_id = uuid.UUID(current_user["user_id"])
    tenants = await tenant_service.list_tenants_for_user(db, user_id)
    return {"items": tenants}


@router.post("")
async def create_tenant(
    body: TenantCreate,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("tenants:write")),
):
    """Create a new tenant (admin only)."""
    tenant = await tenant_service.create_tenant(db, body.name, body.slug)
    return {
        "id": str(tenant.id),
        "name": tenant.name,
        "slug": tenant.slug,
    }


@router.get("/{tenant_id}/users")
async def list_tenant_users(
    tenant_id: str,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("tenants:write")),
):
    """List users in a tenant (admin only)."""
    try:
        tid = uuid.UUID(tenant_id)
    except ValueError:
        raise HTTPException(
            400, detail={"detail": "Invalid tenant_id", "code": "invalid_id"}
        ) from None

    users = await tenant_service.list_tenant_users(db, tid)
    return {"items": users}


@router.post("/{tenant_id}/users")
async def assign_user_to_tenant(
    tenant_id: str,
    body: TenantUserAssign,
    db: AsyncSession = Depends(get_db),
    current_user: dict = Depends(require_permission("tenants:write")),
):
    """Assign a user to a tenant (admin only)."""
    try:
        tid = uuid.UUID(tenant_id)
        uid = uuid.UUID(body.user_id)
    except ValueError:
        raise HTTPException(400, detail={"detail": "Invalid ID", "code": "invalid_id"}) from None

    await tenant_service.assign_user_to_tenant(db, tid, uid)
    return {"message": "User assigned to tenant"}
