"""Referral Code APIs — issue/revoke codes for members (Phase 7.5)."""
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_db, get_pagination, require_tenant
from app.api.permissions import require_permissions
from app.permissions.definitions import (
    LOYALTY_REFERRAL_CODES_CREATE,
    LOYALTY_REFERRAL_CODES_REVOKE,
    LOYALTY_REFERRAL_CODES_VIEW,
)
from app.schemas.referral import (
    ReferralCodeIssueRequest,
    ReferralCodePage,
    ReferralCodeRead,
)
from app.services.referral_engine import ReferralEngineService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=ReferralCodeRead, status_code=status.HTTP_201_CREATED)
async def issue_referral_code(
    body: ReferralCodeIssueRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_REFERRAL_CODES_CREATE)),
):
    return await ReferralEngineService(db).issue_code(tenant_id, body, actor=user)


@router.get("", response_model=ReferralCodePage)
async def list_referral_codes(
    referral_program_id: UUID | None = None,
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOYALTY_REFERRAL_CODES_VIEW)),
):
    rows, total = await ReferralEngineService(db).list_codes(
        tenant_id,
        offset=pagination.offset,
        limit=pagination.page_size,
        referral_program_id=referral_program_id,
    )
    return ReferralCodePage(
        items=rows, total=total, offset=pagination.offset, limit=pagination.page_size
    )


@router.get("/{code_id}", response_model=ReferralCodeRead)
async def get_referral_code(
    code_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOYALTY_REFERRAL_CODES_VIEW)),
):
    return await ReferralEngineService(db).get_code(tenant_id, code_id)


@router.post("/{code_id}/revoke", response_model=ReferralCodeRead)
async def revoke_referral_code(
    code_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_REFERRAL_CODES_REVOKE)),
):
    return await ReferralEngineService(db).revoke_code(tenant_id, code_id, actor=user)
