"""Pricing rule APIs — Phase 10.4."""
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.commands.pricing import PricingCommands
from app.models.types import PricingRuleStatus
from app.permissions.definitions import (
    PRICING_RULES_CREATE,
    PRICING_RULES_DELETE,
    PRICING_RULES_UPDATE,
    PRICING_RULES_VIEW,
)
from app.queries.pricing import PricingQueries
from app.schemas.pricing import (
    PricingRuleCreate,
    PricingRuleListResponse,
    PricingRuleRead,
    PricingRuleUpdate,
)
from app.specifications.pricing import PricingRuleListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    status_filter: PricingRuleStatus | None = Query(default=None, alias="status"),
    organization_id: UUID | None = Query(default=None),
    q: str | None = Query(default=None, max_length=100),
    sort_by: str = Query(default="created_at"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> PricingRuleListSpec:
    return PricingRuleListSpec(
        status=status_filter,
        organization_id=organization_id,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post("", response_model=PricingRuleRead, status_code=status.HTTP_201_CREATED)
async def create_pricing_rule(
    body: PricingRuleCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(PRICING_RULES_CREATE)),
):
    return await PricingCommands(db).create_rule(tenant_id, body, actor=user)


@router.get("", response_model=PricingRuleListResponse)
async def list_pricing_rules(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: PricingRuleListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(PRICING_RULES_VIEW)),
):
    items, total = await PricingQueries(db).list_rules(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return PricingRuleListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{rule_id}", response_model=PricingRuleRead)
async def get_pricing_rule(
    rule_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(PRICING_RULES_VIEW)),
):
    return await PricingQueries(db).get_rule(tenant_id, rule_id)


@router.patch("/{rule_id}", response_model=PricingRuleRead)
async def update_pricing_rule(
    rule_id: UUID,
    body: PricingRuleUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(PRICING_RULES_UPDATE)),
):
    return await PricingCommands(db).update_rule(tenant_id, rule_id, body, actor=user)


@router.post("/{rule_id}/delete", response_model=PricingRuleRead)
async def delete_pricing_rule(
    rule_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(PRICING_RULES_DELETE)),
):
    return await PricingCommands(db).delete_rule(tenant_id, rule_id, actor=user)
