"""Settlement APIs — Phase 10.8."""
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.settlement import SettlementCommands
from app.models.types import SettlementIntentStatus
from app.permissions.definitions import (
    SETTLEMENTS_CREATE,
    SETTLEMENTS_LINES_MANAGE,
    SETTLEMENTS_LINES_VIEW,
    SETTLEMENTS_STATUS,
    SETTLEMENTS_UPDATE,
    SETTLEMENTS_VIEW,
)
from app.queries.settlement import SettlementQueries
from app.schemas.settlement import (
    SettlementActionRequest,
    SettlementIntentCreate,
    SettlementIntentListResponse,
    SettlementIntentRead,
    SettlementIntentUpdate,
    SettlementLineCreate,
    SettlementLineRead,
)
from app.specifications.settlement import SettlementIntentListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()


def _list_spec(
    status_filter: SettlementIntentStatus | None = Query(default=None, alias="status"),
    organization_id: UUID | None = Query(default=None),
    driver_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)$"),
) -> SettlementIntentListSpec:
    return SettlementIntentListSpec(
        status=status_filter,
        organization_id=organization_id,
        driver_id=driver_id,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post("", response_model=SettlementIntentRead, status_code=status.HTTP_201_CREATED)
async def create_settlement(
    body: SettlementIntentCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SETTLEMENTS_CREATE)),
):
    return await SettlementCommands(db).create(tenant_id, body, actor=user)


@router.get("", response_model=SettlementIntentListResponse)
async def list_settlements(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: SettlementIntentListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(SETTLEMENTS_VIEW)),
):
    items, total = await SettlementQueries(db).list(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return SettlementIntentListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{intent_id}", response_model=SettlementIntentRead)
async def get_settlement(
    intent_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(SETTLEMENTS_VIEW)),
):
    return await SettlementQueries(db).get(tenant_id, intent_id)


@router.patch("/{intent_id}", response_model=SettlementIntentRead)
async def update_settlement(
    intent_id: UUID,
    body: SettlementIntentUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SETTLEMENTS_UPDATE)),
):
    return await SettlementCommands(db).update(tenant_id, intent_id, body, actor=user)


@router.post("/{intent_id}/submit", response_model=SettlementIntentRead)
async def submit_settlement(
    intent_id: UUID,
    body: SettlementActionRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SETTLEMENTS_STATUS)),
):
    return await SettlementCommands(db).submit(tenant_id, intent_id, body, actor=user)


@router.post("/{intent_id}/settle", response_model=SettlementIntentRead)
async def settle_settlement(
    intent_id: UUID,
    body: SettlementActionRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SETTLEMENTS_STATUS)),
):
    return await SettlementCommands(db).settle(tenant_id, intent_id, body, actor=user)


@router.post("/{intent_id}/fail", response_model=SettlementIntentRead)
async def fail_settlement(
    intent_id: UUID,
    body: SettlementActionRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SETTLEMENTS_STATUS)),
):
    return await SettlementCommands(db).fail(tenant_id, intent_id, body, actor=user)


@router.post("/{intent_id}/cancel", response_model=SettlementIntentRead)
async def cancel_settlement(
    intent_id: UUID,
    body: SettlementActionRequest,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SETTLEMENTS_STATUS)),
):
    return await SettlementCommands(db).cancel(tenant_id, intent_id, body, actor=user)


@router.post(
    "/{intent_id}/lines",
    response_model=SettlementLineRead,
    status_code=status.HTTP_201_CREATED,
)
async def add_settlement_line(
    intent_id: UUID,
    body: SettlementLineCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(SETTLEMENTS_LINES_MANAGE)),
):
    return await SettlementCommands(db).add_line(tenant_id, intent_id, body, actor=user)


@router.get("/{intent_id}/lines", response_model=list[SettlementLineRead])
async def list_settlement_lines(
    intent_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(SETTLEMENTS_LINES_VIEW)),
):
    return await SettlementQueries(db).lines(tenant_id, intent_id)
