"""Reward redemption lifecycle APIs — Phase 7.3."""
from __future__ import annotations

from uuid import UUID

from fastapi import APIRouter, Depends, Query
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.models.types import RedemptionStatus
from app.permissions.definitions import (
    LOYALTY_REDEMPTIONS_VIEW,
    LOYALTY_REWARDS_CANCEL,
    LOYALTY_REWARDS_FULFILL,
)
from app.schemas.rewards import CancelRequest, RewardRedemptionPage, RewardRedemptionRead
from app.services.rewards_engine import RewardsEngineService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.get("", response_model=RewardRedemptionPage)
async def list_redemptions(
    status: RedemptionStatus | None = Query(default=None),
    member_id: UUID | None = Query(default=None),
    reward_id: UUID | None = Query(default=None),
    pagination: PaginationParams = Depends(get_pagination),
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOYALTY_REDEMPTIONS_VIEW)),
):
    rows, total = await RewardsEngineService(db).list(
        tenant_id,
        reward_id=reward_id,
        member_id=member_id,
        status=status,
        offset=pagination.offset,
        limit=pagination.page_size,
    )
    return RewardRedemptionPage(
        items=rows, total=total, offset=pagination.offset, limit=pagination.page_size
    )


@router.get("/{redemption_id}", response_model=RewardRedemptionRead)
async def get_redemption(
    redemption_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOYALTY_REDEMPTIONS_VIEW)),
):
    return await RewardsEngineService(db).get(tenant_id, redemption_id)


@router.post("/{redemption_id}/fulfill", response_model=RewardRedemptionRead)
async def fulfill_redemption(
    redemption_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_REWARDS_FULFILL)),
):
    return await RewardsEngineService(db).fulfill(tenant_id, redemption_id, actor=user)


@router.post("/{redemption_id}/cancel", response_model=RewardRedemptionRead)
async def cancel_redemption(
    redemption_id: UUID,
    body: CancelRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_REWARDS_CANCEL)),
):
    return await RewardsEngineService(db).cancel(
        tenant_id, redemption_id, body, actor=user
    )
