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

from src.apps.tenants.schemas.requests import UpdateTenantRequest, UpdateBrandingRequest
from src.apps.tenants.schemas.responses import AccountDetailResponse, BrandingResponse
from src.apps.tenants.services.tenant_service import TenantService
from src.core.dependencies import get_current_user, require_roles
from src.core.constants import UserRole
from src.core.schemas.response import success
from src.database.session import get_db

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


@router.get("/me", response_model=dict)
async def get_my_tenant(
    current_user=Depends(require_roles(
        UserRole.ADMINISTRATOR, UserRole.MANAGER, UserRole.STAFF, UserRole.VIEW_ONLY
    )),
    db: AsyncSession = Depends(get_db),
):
    """Get current user's tenant (cemetery) details."""
    service = TenantService(db)
    account = await service.get_by_id(current_user.tenant_id)
    return success(data=AccountDetailResponse.model_validate(account).model_dump())


@router.patch("/me", response_model=dict)
async def update_my_tenant(
    body: UpdateTenantRequest,
    current_user=Depends(require_roles(UserRole.ADMINISTRATOR)),
    db: AsyncSession = Depends(get_db),
):
    service = TenantService(db)
    account = await service.update(current_user.tenant_id, body.model_dump(exclude_none=True))
    return success(
        data=AccountDetailResponse.model_validate(account).model_dump(),
        message="Cemetery profile updated",
    )


@router.get("/me/branding", response_model=dict)
async def get_branding(
    current_user=Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    service = TenantService(db)
    account = await service.get_by_id(current_user.tenant_id)
    branding = account.branding if account else None
    return success(
        data=BrandingResponse.model_validate(branding).model_dump() if branding else {}
    )


@router.patch("/me/branding", response_model=dict)
async def update_branding(
    body: UpdateBrandingRequest,
    current_user=Depends(require_roles(UserRole.ADMINISTRATOR)),
    db: AsyncSession = Depends(get_db),
):
    service = TenantService(db)
    branding = await service.update_branding(
        current_user.tenant_id, body.model_dump(exclude_none=True)
    )
    return success(
        data=BrandingResponse.model_validate(branding).model_dump(),
        message="Branding updated",
    )
