"""Loyalty program APIs — Phase 7.0."""
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_PROGRAMS_CREATE,
    LOYALTY_PROGRAMS_DELETE,
    LOYALTY_PROGRAMS_UPDATE,
    LOYALTY_PROGRAMS_VIEW,
)
from app.schemas.foundation import (
    LoyaltyProgramCreate,
    LoyaltyProgramRead,
    LoyaltyProgramUpdate,
)
from app.services.foundation import LoyaltyProgramService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=LoyaltyProgramRead, status_code=status.HTTP_201_CREATED)
async def create_program(
    body: LoyaltyProgramCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_PROGRAMS_CREATE)),
):
    return await LoyaltyProgramService(db).create(tenant_id, body, actor=user)


@router.get("", response_model=list[LoyaltyProgramRead])
async def list_programs(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOYALTY_PROGRAMS_VIEW)),
):
    return await LoyaltyProgramService(db).list(
        tenant_id, offset=pagination.offset, limit=pagination.page_size
    )


@router.get("/{program_id}", response_model=LoyaltyProgramRead)
async def get_program(
    program_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOYALTY_PROGRAMS_VIEW)),
):
    return await LoyaltyProgramService(db).get(tenant_id, program_id)


@router.patch("/{program_id}", response_model=LoyaltyProgramRead)
async def update_program(
    program_id: UUID,
    body: LoyaltyProgramUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_PROGRAMS_UPDATE)),
):
    return await LoyaltyProgramService(db).update(
        tenant_id, program_id, body, actor=user
    )


@router.post("/{program_id}/delete", response_model=LoyaltyProgramRead)
async def soft_delete_program(
    program_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_PROGRAMS_DELETE)),
):
    return await LoyaltyProgramService(db).soft_delete(
        tenant_id, program_id, actor=user
    )
