import dataclasses
from typing import Annotated

from fastapi import HTTPException, Request, UploadFile
from fastapi.params import File
from folkugat_web.api.router import get_router
from folkugat_web.fragments.sessio import cartell
from folkugat_web.services import auth
from folkugat_web.services import files as files_service
from folkugat_web.services import sessions as sessions_service

router = get_router()


@router.get("/api/sessio/{session_id}/cartell")
def get_cartell(
    request: Request,
    logged_in: auth.LoggedIn,
    session_id: int,
):
    return cartell.cartell(request, session_id, logged_in)


@router.get("/api/sessio/{session_id}/cartell/editor")
def get_cartell_editor(
    request: Request,
    _: auth.RequireLogin,
    session_id: int,
):
    return cartell.cartell_editor(request, session_id)


@router.put("/api/sessio/{session_id}/cartell")
async def set_cartell(
    request: Request,
    logged_in: auth.RequireLogin,
    session_id: int,
    upload_file: Annotated[UploadFile, File()],
):
    session = sessions_service.get_session(session_id=session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Could not find session")
    url = await files_service.store_session_cartell(
        session_id=session_id,
        upload_file=upload_file,
    )
    new_session = dataclasses.replace(
        session,
        cartell_url=url,
    )
    sessions_service.set_session(new_session)
    return cartell.cartell(request, session_id, logged_in)


@router.delete("/api/sessio/{session_id}/cartell")
async def delete_cartell(
    request: Request,
    logged_in: auth.RequireLogin,
    session_id: int,
):
    session = sessions_service.get_session(session_id=session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Could not find session")
    if session.cartell_url:
        new_session = dataclasses.replace(
            session,
            cartell_url=None,
        )
        sessions_service.set_session(new_session)
        files_service.clean_orphan_files()
    return cartell.cartell(request, session_id, logged_in)
