"""Campaign APIs — CRUD (7.0) + lifecycle, rules versioning, and apply (7.4)."""
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_CAMPAIGNS_ACTIVATE,
    LOYALTY_CAMPAIGNS_APPLICATIONS_VIEW,
    LOYALTY_CAMPAIGNS_APPLY,
    LOYALTY_CAMPAIGNS_CREATE,
    LOYALTY_CAMPAIGNS_DELETE,
    LOYALTY_CAMPAIGNS_EXPIRE,
    LOYALTY_CAMPAIGNS_PAUSE,
    LOYALTY_CAMPAIGNS_RESUME,
    LOYALTY_CAMPAIGNS_RULES_UPDATE,
    LOYALTY_CAMPAIGNS_SCHEDULE,
    LOYALTY_CAMPAIGNS_UPDATE,
    LOYALTY_CAMPAIGNS_VIEW,
)
from app.schemas.campaigns import (
    ApplyCampaignRequest,
    CampaignApplicationPage,
    CampaignApplicationRead,
    CampaignRulesUpdateRequest,
)
from app.schemas.foundation import CampaignCreate, CampaignRead, CampaignUpdate
from app.services.campaign_engine import CampaignEngineService
from app.services.foundation import CampaignService
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


@router.post("", response_model=CampaignRead, status_code=status.HTTP_201_CREATED)
async def create_campaign(
    body: CampaignCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_CAMPAIGNS_CREATE)),
):
    return await CampaignService(db).create(tenant_id, body, actor=user)


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


@router.get("/{campaign_id}", response_model=CampaignRead)
async def get_campaign(
    campaign_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(LOYALTY_CAMPAIGNS_VIEW)),
):
    return await CampaignService(db).get(tenant_id, campaign_id)


@router.patch("/{campaign_id}", response_model=CampaignRead)
async def update_campaign(
    campaign_id: UUID,
    body: CampaignUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_CAMPAIGNS_UPDATE)),
):
    return await CampaignService(db).update(
        tenant_id, campaign_id, body, actor=user
    )


@router.post("/{campaign_id}/delete", response_model=CampaignRead)
async def soft_delete_campaign(
    campaign_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_CAMPAIGNS_DELETE)),
):
    return await CampaignService(db).soft_delete(
        tenant_id, campaign_id, actor=user
    )


@router.post("/{campaign_id}/schedule", response_model=CampaignRead)
async def schedule_campaign(
    campaign_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_CAMPAIGNS_SCHEDULE)),
):
    return await CampaignEngineService(db).schedule(tenant_id, campaign_id, actor=user)


@router.post("/{campaign_id}/activate", response_model=CampaignRead)
async def activate_campaign(
    campaign_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_CAMPAIGNS_ACTIVATE)),
):
    return await CampaignEngineService(db).activate(tenant_id, campaign_id, actor=user)


@router.post("/{campaign_id}/pause", response_model=CampaignRead)
async def pause_campaign(
    campaign_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_CAMPAIGNS_PAUSE)),
):
    return await CampaignEngineService(db).pause(tenant_id, campaign_id, actor=user)


@router.post("/{campaign_id}/resume", response_model=CampaignRead)
async def resume_campaign(
    campaign_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_CAMPAIGNS_RESUME)),
):
    return await CampaignEngineService(db).resume(tenant_id, campaign_id, actor=user)


@router.post("/{campaign_id}/expire", response_model=CampaignRead)
async def expire_campaign(
    campaign_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_CAMPAIGNS_EXPIRE)),
):
    return await CampaignEngineService(db).expire(tenant_id, campaign_id, actor=user)


@router.post("/{campaign_id}/rules", response_model=CampaignRead)
async def update_campaign_rules(
    campaign_id: UUID,
    body: CampaignRulesUpdateRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_CAMPAIGNS_RULES_UPDATE)),
):
    return await CampaignEngineService(db).update_rules(
        tenant_id, campaign_id, body, actor=user
    )


@router.post(
    "/{campaign_id}/apply",
    response_model=CampaignApplicationRead,
    status_code=status.HTTP_201_CREATED,
)
async def apply_campaign(
    campaign_id: UUID,
    body: ApplyCampaignRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(LOYALTY_CAMPAIGNS_APPLY)),
):
    return await CampaignEngineService(db).apply(
        tenant_id, campaign_id, body, actor=user
    )


@router.get("/{campaign_id}/applications", response_model=CampaignApplicationPage)
async def list_campaign_applications(
    campaign_id: UUID,
    pagination: PaginationParams = Depends(get_pagination),
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(
        require_permissions(
            LOYALTY_CAMPAIGNS_APPLICATIONS_VIEW, LOYALTY_CAMPAIGNS_VIEW
        )
    ),
):
    rows, total = await CampaignEngineService(db).list_applications(
        tenant_id, campaign_id, offset=pagination.offset, limit=pagination.page_size
    )
    return CampaignApplicationPage(
        items=rows, total=total, offset=pagination.offset, limit=pagination.page_size
    )
