# retoor <retoor@molodetz.nl>

import logging
from fastapi import APIRouter, Request
from devplacepy.database import get_table, _now_iso
from devplacepy.utils import get_current_user, clear_session_cache
from devplacepy.responses import action_result
from devplacepy.services.audit import record as audit

logger = logging.getLogger(__name__)
router = APIRouter()


@router.get("/logout")
async def logout(request: Request):
    user = get_current_user(request)
    token = request.cookies.get("session")
    if token:
        sessions = get_table("sessions")
        session = sessions.find_one(session_token=token, deleted_at=None)
        if session:
            sessions.update(
                {
                    "id": session["id"],
                    "deleted_at": _now_iso(),
                    "deleted_by": session["user_uid"],
                },
                ["id"],
            )
        clear_session_cache(token)
    if user:
        audit.record(
            request,
            "auth.logout",
            user=user,
            target_type="user",
            target_uid=user["uid"],
            target_label=user.get("username"),
            summary=f"user {user.get('username')} logged out",
            links=[audit.target("user", user["uid"], user.get("username"))],
        )
    response = action_result(request, "/")
    response.delete_cookie("session")
    return response
