"""Template version APIs — Phase 11.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.templates import TemplateCommands
from app.permissions.definitions import (
    TEMPLATES_CREATE,
    TEMPLATES_MANAGE,
    TEMPLATES_UPDATE,
    TEMPLATES_VIEW,
)
from app.queries.templates import TemplateQueries
from app.schemas.templates import (
    ExperienceTemplateVersionCreate,
    ExperienceTemplateVersionListResponse,
    ExperienceTemplateVersionRead,
    ExperienceTemplateVersionUpdate,
)
from app.specifications.templates import (
    TEMPLATE_VERSION_SORT_FIELDS,
    TemplateVersionListSpec,
)
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

_STATUSES = {"draft", "published", "retired"}


def _list_spec(
    template_id: UUID | None = Query(default=None),
    status_filter: str | None = Query(default=None, alias="status"),
    q: str | None = Query(default=None, max_length=100),
    sort_by: str = Query(default="version_number"),
    sort_dir: str = Query(default="desc", pattern="^(?i)(asc|desc)$"),
) -> TemplateVersionListSpec:
    if sort_by not in TEMPLATE_VERSION_SORT_FIELDS:
        sort_by = "version_number"
    return TemplateVersionListSpec(
        template_id=template_id,
        status=status_filter if status_filter in _STATUSES else None,
        q=q,
        sort_by=sort_by,
        sort_dir=sort_dir.lower(),
    )


@router.post(
    "",
    response_model=ExperienceTemplateVersionRead,
    status_code=status.HTTP_201_CREATED,
)
async def create_version(
    body: ExperienceTemplateVersionCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TEMPLATES_CREATE)),
):
    return await TemplateCommands(db).create_version(tenant_id, body, actor=user)


@router.get("", response_model=ExperienceTemplateVersionListResponse)
async def list_versions(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: TemplateVersionListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(TEMPLATES_VIEW)),
):
    items, total = await TemplateQueries(db).list_versions(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return ExperienceTemplateVersionListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{version_id}", response_model=ExperienceTemplateVersionRead)
async def get_version(
    version_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(TEMPLATES_VIEW)),
):
    return await TemplateQueries(db).get_version(tenant_id, version_id)


@router.patch("/{version_id}", response_model=ExperienceTemplateVersionRead)
async def update_version(
    version_id: UUID,
    body: ExperienceTemplateVersionUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TEMPLATES_UPDATE)),
):
    return await TemplateCommands(db).update_version(
        tenant_id, version_id, body, actor=user
    )


@router.post("/{version_id}/publish", response_model=ExperienceTemplateVersionRead)
async def publish_version(
    version_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TEMPLATES_MANAGE)),
):
    return await TemplateCommands(db).publish_version(
        tenant_id, version_id, actor=user
    )


@router.post("/{version_id}/retire", response_model=ExperienceTemplateVersionRead)
async def retire_version(
    version_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(TEMPLATES_MANAGE)),
):
    return await TemplateCommands(db).retire_version(
        tenant_id, version_id, actor=user
    )
