"""APIهای Tenant Context جاری: `/tenant/current` و `/tenant/switch`."""
from __future__ import annotations

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

from app.api.deps import get_current_core_user, get_db
from app.models.enums import MembershipStatus
from app.models.user import User
from app.repositories.tenant import TenantRepository
from app.schemas.onboarding import TenantContextRead, TenantSwitchRequest
from app.services.membership_service import MembershipService
from app.services.tenant_context_service import TenantContextService
from shared.exceptions import ForbiddenError, NotFoundError

router = APIRouter(prefix="/tenant", tags=["tenant-context"])


@router.get("/current", response_model=TenantContextRead)
async def get_current_tenant(
    db: AsyncSession = Depends(get_db),
    core_user: User = Depends(get_current_core_user),
) -> TenantContextRead:
    ctx_service = TenantContextService(db)
    tenant = await ctx_service.resolve_current_tenant(core_user)
    return await ctx_service.build(tenant, core_user)


@router.post("/switch", response_model=TenantContextRead)
async def switch_tenant(
    payload: TenantSwitchRequest,
    db: AsyncSession = Depends(get_db),
    core_user: User = Depends(get_current_core_user),
) -> TenantContextRead:
    membership = await MembershipService(db).get(payload.tenant_id, core_user.id)
    if membership is None or membership.status != MembershipStatus.ACTIVE:
        raise ForbiddenError("عضو این tenant نیستید یا عضویت غیرفعال است")

    core_user.current_tenant_id = payload.tenant_id
    await db.commit()

    tenant = await TenantRepository(db).get(payload.tenant_id)
    if tenant is None:
        raise NotFoundError(f"tenant یافت نشد: {payload.tenant_id}")
    ctx_service = TenantContextService(db)
    return await ctx_service.build(tenant, core_user)
