"""Media reference APIs — Phase 11.5 (Storage refs only)."""
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.localization import LocalizationCommands
from app.permissions.definitions import (
    MEDIA_REFS_CREATE,
    MEDIA_REFS_DELETE,
    MEDIA_REFS_UPDATE,
    MEDIA_REFS_VIEW,
)
from app.queries.localization import LocalizationQueries
from app.schemas.localization import (
    ExperienceMediaRefCreate,
    ExperienceMediaRefListResponse,
    ExperienceMediaRefRead,
    ExperienceMediaRefUpdate,
)
from app.specifications.localization import MEDIA_REF_SORT_FIELDS, MediaRefListSpec
from shared.pagination import PaginationParams
from shared.security import CurrentUser

router = APIRouter()

_KINDS = {"image", "video", "document", "audio", "icon", "other"}
_STATUSES = {"draft", "active", "archived"}


def _list_spec(
    workspace_id: UUID | None = Query(default=None),
    site_id: UUID | None = Query(default=None),
    page_id: UUID | None = Query(default=None),
    owner_type: str | None = Query(default=None, max_length=50),
    owner_id: UUID | None = Query(default=None),
    kind: str | None = Query(default=None, max_length=20),
    locale: str | None = Query(default=None, max_length=16),
    status_filter: str | None = Query(default=None, alias="status"),
    q: str | None = Query(default=None, max_length=100),
    sort_by: str = Query(default="sort_order"),
    sort_dir: str = Query(default="asc", pattern="^(?i)(asc|desc)$"),
) -> MediaRefListSpec:
    if sort_by not in MEDIA_REF_SORT_FIELDS:
        sort_by = "sort_order"
    return MediaRefListSpec(
        workspace_id=workspace_id,
        site_id=site_id,
        page_id=page_id,
        owner_type=owner_type,
        owner_id=owner_id,
        kind=kind if kind in _KINDS else None,
        locale=locale,
        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=ExperienceMediaRefRead, status_code=status.HTTP_201_CREATED
)
async def create_media_ref(
    body: ExperienceMediaRefCreate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(MEDIA_REFS_CREATE)),
):
    return await LocalizationCommands(db).create_media_ref(tenant_id, body, actor=user)


@router.get("", response_model=ExperienceMediaRefListResponse)
async def list_media_refs(
    tenant_id: UUID = Depends(require_tenant),
    pagination: PaginationParams = Depends(get_pagination),
    spec: MediaRefListSpec = Depends(_list_spec),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(MEDIA_REFS_VIEW)),
):
    items, total = await LocalizationQueries(db).list_media_refs(
        tenant_id, offset=pagination.offset, limit=pagination.page_size, spec=spec
    )
    return ExperienceMediaRefListResponse(
        items=items, total=total, page=pagination.page, page_size=pagination.page_size
    )


@router.get("/{media_ref_id}", response_model=ExperienceMediaRefRead)
async def get_media_ref(
    media_ref_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    _user: CurrentUser = Depends(require_permissions(MEDIA_REFS_VIEW)),
):
    return await LocalizationQueries(db).get_media_ref(tenant_id, media_ref_id)


@router.patch("/{media_ref_id}", response_model=ExperienceMediaRefRead)
async def update_media_ref(
    media_ref_id: UUID,
    body: ExperienceMediaRefUpdate,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(MEDIA_REFS_UPDATE)),
):
    return await LocalizationCommands(db).update_media_ref(
        tenant_id, media_ref_id, body, actor=user
    )


@router.delete("/{media_ref_id}", response_model=ExperienceMediaRefRead)
async def delete_media_ref(
    media_ref_id: UUID,
    tenant_id: UUID = Depends(require_tenant),
    db: AsyncSession = Depends(get_db),
    user: CurrentUser = Depends(require_permissions(MEDIA_REFS_DELETE)),
):
    return await LocalizationCommands(db).soft_delete_media_ref(
        tenant_id, media_ref_id, actor=user
    )
