from io import BytesIO

from dishka import FromDishka
from dishka.integrations.fastapi import DishkaRoute
from fastapi import APIRouter, Depends, UploadFile
from fastapi.security import HTTPBearer
from pydantic import BaseModel, Field
from uuid_utils.compat import uuid7

from template_project.application.common.file_storage import FileStorage

security = HTTPBearer()
router = APIRouter(route_class=DishkaRoute, tags=["Storage"], dependencies=[Depends(security)])


class UploadFileResponse(BaseModel):
    path: str = Field(..., description="Generated file path (UUID7)")

    model_config = {"json_schema_extra": {"example": {"path": "01234567-89ab-cdef-0123-456789abcdef"}}}


@router.post(
    "/storage/upload_file",
    summary="Upload file",
    description="Upload a file to storage. The file path is automatically generated using UUID7.",
    responses={
        200: {"description": "File uploaded successfully", "model": UploadFileResponse},
        401: {"description": "Unauthorized - invalid or missing token"},
        413: {"description": "File too large"},
    },
)
async def upload_file(
    file: UploadFile,
    file_storage: FromDishka[FileStorage],
) -> UploadFileResponse:
    path = str(uuid7())
    file_content = await file.read()
    file_io = BytesIO(file_content)
    await file_storage.upload(path=path, image=file_io)
    return UploadFileResponse(path=path)
