"""APIهای Onboarding: ایجاد و فعال‌سازی tenant توسط کاربر جاری."""
from __future__ import annotations

from uuid import UUID

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

from app.api.deps import get_current_core_user, get_db
from app.core.security import get_current_user
from app.models.user import User
from app.schemas.onboarding import (
    OnboardingBrandingUpdate,
    OnboardingDomainUpdate,
    OnboardingTenantCreate,
    TenantContextRead,
)
from app.services.membership_service import MembershipService
from app.services.onboarding_service import OnboardingService
from app.services.tenant_context_service import TenantContextService
from shared.security import CurrentUser

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


@router.post("", response_model=TenantContextRead, status_code=status.HTTP_201_CREATED)
async def create_onboarding_tenant(
    payload: OnboardingTenantCreate,
    db: AsyncSession = Depends(get_db),
    core_user: User = Depends(get_current_core_user),
) -> TenantContextRead:
    tenant = await OnboardingService(db).create_tenant(core_user, payload)
    return await TenantContextService(db).build(tenant, core_user)


@router.patch("/{tenant_id}/branding", response_model=TenantContextRead)
async def update_onboarding_branding(
    tenant_id: UUID,
    payload: OnboardingBrandingUpdate,
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
    core_user: User = Depends(get_current_core_user),
) -> TenantContextRead:
    await MembershipService(db).ensure_role(
        tenant_id=tenant_id, core_user_id=core_user.id, current_user=user
    )
    tenant = await OnboardingService(db).update_branding(tenant_id, payload)
    return await TenantContextService(db).build(tenant, core_user)


@router.patch("/{tenant_id}/domain", response_model=TenantContextRead)
async def update_onboarding_domain(
    tenant_id: UUID,
    payload: OnboardingDomainUpdate,
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
    core_user: User = Depends(get_current_core_user),
) -> TenantContextRead:
    await MembershipService(db).ensure_role(
        tenant_id=tenant_id, core_user_id=core_user.id, current_user=user
    )
    tenant = await OnboardingService(db).update_domain(tenant_id, payload)
    return await TenantContextService(db).build(tenant, core_user)


@router.post("/{tenant_id}/complete", response_model=TenantContextRead)
async def complete_onboarding(
    tenant_id: UUID,
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(get_current_user),
    core_user: User = Depends(get_current_core_user),
) -> TenantContextRead:
    await MembershipService(db).ensure_role(
        tenant_id=tenant_id, core_user_id=core_user.id, current_user=user
    )
    tenant = await OnboardingService(db).complete(tenant_id)
    return await TenantContextService(db).build(tenant, core_user)
