# retoor <retoor@molodetz.nl>

from fastapi import APIRouter, Request
from fastapi.responses import RedirectResponse
from devplacepy.attachments import _row_to_attachment
from devplacepy.database import get_table, resolve_by_slug
from devplacepy.utils import not_found

router = APIRouter()

_VALID_SIZES = {"512", "256", "64"}
_CACHE_CONTROL = "public, max-age=86400, immutable"


@router.get("/{slug_or_uid}/{size}")
async def award_image(request: Request, slug_or_uid: str, size: str):
    if size not in _VALID_SIZES:
        raise not_found("Award image not found")
    award = resolve_by_slug(get_table("awards"), slug_or_uid)
    if not award or not award.get("generated_at"):
        raise not_found("Award image not found")
    attachment_uid = award.get(f"attachment_uid_{size}") or ""
    if not attachment_uid:
        raise not_found("Award image not found")
    row = get_table("attachments").find_one(uid=attachment_uid, deleted_at=None)
    attachment = _row_to_attachment(row) if row else None
    if not attachment:
        raise not_found("Award image not found")
    url = attachment.get("url") or ""
    if not url:
        raise not_found("Award image not found")
    headers = {
        "Cache-Control": _CACHE_CONTROL,
        "ETag": f'"{attachment_uid}"',
    }
    return RedirectResponse(url=url, status_code=302, headers=headers)