from typing import Annotated

from fastapi import Cookie, Form, Request
from folkugat_web.api.router import get_router
from folkugat_web.config import auth as config
from folkugat_web.fragments import nota
from folkugat_web.services import auth as service

router = get_router()


@router.get("/api/nota")
def nota_input(request: Request, value: str | None = None):
    return nota.input(request, value)


@router.post("/api/nota")
def login(request: Request, value: Annotated[str | None, Form()] = None,
          nota_folkugat: Annotated[str | None, Cookie()] = None):
    logged_in = service.logged_in(nota_folkugat)
    new_login = service.login(value)
    if new_login and not logged_in:
        response = nota.nota(request)
        response.set_cookie(key=config.COOKIE_NAME,
                            value=service.build_token(),
                            max_age=config.COOKIE_MAX_AGE)
    else:
        response = nota.footer(request, value, logged_in)
    return response


@router.post("/api/logout")
def logout(request: Request):
    response = nota.nota(request)
    response.delete_cookie(key=config.COOKIE_NAME)
    return response
