"""API `/me`: هویت جاری، عضویت‌ها و نیاز به onboarding."""
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.user import User
from app.schemas.onboarding import MembershipSummary, MeResponse
from app.services.tenant_context_service import TenantContextService

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


@router.get("", response_model=MeResponse)
async def get_me(
    db: AsyncSession = Depends(get_db),
    core_user: User = Depends(get_current_core_user),
) -> MeResponse:
    memberships = await TenantContextService(db).list_memberships_summary(core_user)

    onboarding_required = True
    if memberships:
        current = next(
            (m for m in memberships if m.tenant_id == core_user.current_tenant_id),
            memberships[0],
        )
        onboarding_required = not current.onboarding_completed

    return MeResponse(
        user_id=core_user.id,
        mobile=core_user.mobile,
        email=core_user.email,
        platform_role=core_user.role.value,
        onboarding_required=onboarding_required,
        current_tenant_id=core_user.current_tenant_id,
        memberships=memberships,
    )


@router.get("/tenants", response_model=list[MembershipSummary])
async def get_my_tenants(
    db: AsyncSession = Depends(get_db),
    core_user: User = Depends(get_current_core_user),
) -> list[MembershipSummary]:
    return await TenantContextService(db).list_memberships_summary(core_user)
