from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import Response

from app.core.media_signing import verify_signed_media
from app.core.storage import download_object

router = APIRouter()


@router.get("/files/{file_path:path}")
async def get_media_file(
    file_path: str,
    expires: int = Query(...),
    sig: str = Query(...),
):
    if not file_path.startswith("avatars/"):
        raise HTTPException(status_code=404, detail="FILE_NOT_FOUND")
    if not verify_signed_media(file_path, expires, sig):
        raise HTTPException(status_code=403, detail="INVALID_SIGNATURE")
    stored = download_object(file_path)
    if not stored:
        raise HTTPException(status_code=404, detail="FILE_NOT_FOUND")
    body, content_type = stored
    return Response(content=body, media_type=content_type)
