"""Membership tier APIs — Phase 7.0."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, Query, 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_TIERS_CREATE,
    LOYALTY_TIERS_DELETE,
    LOYALTY_TIERS_UPDATE,
    LOYALTY_TIERS_VIEW,
)
from app.schemas.foundation import (
    MembershipTierCreate,
    MembershipTierRead,
    MembershipTierUpdate,
)
from app.services.foundation import MembershipTierService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=MembershipTierRead, status_code=status.HTTP_201_CREATED)
async def create_tier(
    body: MembershipTierCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_TIERS_CREATE)),
):
    return await MembershipTierService(db).create(tenant_id, body, actor=user)


@router.get("", response_model=list[MembershipTierRead])
async def list_tiers(
    program_id: UUID | None = Query(default=None),
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOYALTY_TIERS_VIEW)),
):
    service = MembershipTierService(db)
    if program_id is not None:
        return await service.list_by_program(
            tenant_id,
            program_id,
            offset=pagination.offset,
            limit=pagination.page_size,
        )
    return await service.list(
        tenant_id, offset=pagination.offset, limit=pagination.page_size
    )


@router.get("/{tier_id}", response_model=MembershipTierRead)
async def get_tier(
    tier_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOYALTY_TIERS_VIEW)),
):
    return await MembershipTierService(db).get(tenant_id, tier_id)


@router.patch("/{tier_id}", response_model=MembershipTierRead)
async def update_tier(
    tier_id: UUID,
    body: MembershipTierUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_TIERS_UPDATE)),
):
    return await MembershipTierService(db).update(
        tenant_id, tier_id, body, actor=user
    )


@router.post("/{tier_id}/delete", response_model=MembershipTierRead)
async def soft_delete_tier(
    tier_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_TIERS_DELETE)),
):
    return await MembershipTierService(db).soft_delete(tenant_id, tier_id, actor=user)
