"""
Router: załączniki zadań admina (admin tasks).
Ścieżka na dysku: {files_base_dir}/admin_tasks/<uuid>.ext

Endpointy:
  POST   /admin_tasks/upload          – przesyłanie załącznika
  GET    /admin_tasks/file/{filename} – pobieranie załącznika
  DELETE /admin_tasks/file/{filename} – usuwanie załącznika
"""
from __future__ import annotations

import mimetypes

from fastapi import APIRouter, Depends, UploadFile, File
from fastapi.responses import FileResponse

from ..auth import require_api_key
from ..storage import save_file, get_stored_file_path, delete_stored_file

router = APIRouter(prefix="/admin_tasks", tags=["admin_tasks"])

_SUBFOLDER = "admin_tasks"


@router.post("/upload", summary="Prześlij załącznik zadania")
async def upload_file(
    file: UploadFile = File(...),
    _key: str = Depends(require_api_key),
):
    result = await save_file(file, _SUBFOLDER)
    return {"success": True, "data": result}


@router.get("/file/{filename}", summary="Pobierz załącznik zadania")
async def serve_file(
    filename: str,
    inline: int = 0,
    _key: str = Depends(require_api_key),
):
    file_path = get_stored_file_path(_SUBFOLDER, filename)
    mime = mimetypes.guess_type(str(file_path))[0] or "application/octet-stream"
    disposition = "inline" if inline else "attachment"
    return FileResponse(
        path=str(file_path),
        media_type=mime,
        headers={"Content-Disposition": f'{disposition}; filename="{filename}"'},
    )


@router.delete("/file/{filename}", summary="Usuń załącznik zadania")
async def delete_file(
    filename: str,
    _key: str = Depends(require_api_key),
):
    deleted = delete_stored_file(_SUBFOLDER, filename)
    return {"success": deleted}
