"""
Router: ogólne pliki przesyłane przez użytkowników.
Ścieżka na dysku: {files_base_dir}/user_files/uploads/<uuid>.ext

Endpointy:
  POST   /user_files/upload          – przesyłanie pliku użytkownika
  GET    /user_files/file/{filename} – pobieranie pliku użytkownika
  DELETE /user_files/file/{filename} – usuwanie pliku użytkownika
"""
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="/user_files", tags=["user_files"])

_SUBFOLDER = "user_files/uploads"


@router.post("/upload", summary="Prześlij plik użytkownika")
async def upload_user_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 plik użytkownika")
async def serve_user_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ń plik użytkownika")
async def delete_user_file(
    filename: str,
    _key: str = Depends(require_api_key),
):
    deleted = delete_stored_file(_SUBFOLDER, filename)
    return {"success": deleted}
