from typing import Annotated, Sequence

from fastapi import APIRouter, File, HTTPException, UploadFile
from fastapi.params import Depends
from sqlmodel import Session, select

from nyahome.config import config_manager
from nyahome.database import ModelUploadFile, ModelUser, get_session
from nyahome.service.file_service import UPLOAD_DIR, s_get_safe_filename, s_save_upload_file

from .auth import verify_token

file_router = APIRouter(tags=["File"], prefix="/file")


@file_router.get("/")
async def get_files(
    user: Annotated[ModelUser, Depends(verify_token)],
    session: Annotated[Session, Depends(get_session)],
) -> Sequence[ModelUploadFile]:
    files: Sequence[ModelUploadFile] = session.exec(
        select(ModelUploadFile).where(ModelUploadFile.uploader_id == user.id)
    ).all()

    return files


@file_router.post("/upload/")
async def file_upload(
    file: Annotated[UploadFile, File()],
    user: Annotated[ModelUser, Depends(verify_token)],
    session: Annotated[Session, Depends(get_session)],
) -> ModelUploadFile:
    try:
        safe_name = s_get_safe_filename(file.filename)  # type: ignore[arg-type]
        dest_path = UPLOAD_DIR / safe_name
    except TypeError as e:
        raise HTTPException(status_code=400, detail=str(e)) from e

    try:
        await s_save_upload_file(dest_path, file)
    except TypeError as e:
        raise HTTPException(status_code=500, detail=str(e)) from e

    download_url = f"{config_manager.get('site_url', 'http://localhost:9000')}/download/{safe_name}"
    upload_file = ModelUploadFile(
        original_name=file.filename,
        safe_name=safe_name,
        download_url=download_url,
        uploader_id=user.id,
    )
    session.add(upload_file)
    session.commit()
    session.refresh(upload_file)
    return upload_file
