import dataclasses
from typing import Annotated

from fastapi import HTTPException, Request
from fastapi.params import Form
from folkugat_web.api.router import get_router
from folkugat_web.fragments.sessio import notes
from folkugat_web.services import auth
from folkugat_web.services import sessions as sessions_service

router = get_router()


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


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


@router.put("/api/sessio/{session_id}/notes")
async def set_notes(
    request: Request,
    logged_in: auth.RequireLogin,
    session_id: int,
    content: Annotated[str, Form()],
):
    session = sessions_service.get_session(session_id=session_id)
    if not session:
        raise HTTPException(status_code=404, detail="Could not find session")
    new_session = dataclasses.replace(
        session,
        notes=content.strip(),
    )
    sessions_service.set_session(new_session)
    return notes.notes(request, session_id, logged_in)
