from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import FileResponse

from app.api.deps import require_roles
from app.models import AdminUser
from app.schemas.certificate_template import CertificateTemplateOut
from app.services.certificate_templates import get_certificate_template, list_certificate_templates

router = APIRouter()


@router.get("", response_model=list[CertificateTemplateOut])
def list_templates(
    _: AdminUser = Depends(require_roles("system_admin", "certificate_admin", "readonly")),
) -> list[dict[str, object]]:
    return [template.to_dict() for template in list_certificate_templates()]


@router.get("/{template_code}/preview")
def preview_template(template_code: str) -> FileResponse:
    try:
        template = get_certificate_template(template_code)
    except (ValueError, FileNotFoundError) as exc:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc
    return FileResponse(template.asset_path, media_type="image/png")
