from datetime import datetime

from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session

from config import SESSION_COOKIE
from dependencies import create_session_token, get_db

router = APIRouter()
templates = Jinja2Templates(directory="templates")


@router.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
    return templates.TemplateResponse("pages/login.html", {"request": request})


@router.post("/login")
async def login(request: Request, kuerzel: str = Form(...), passwort: str = Form(...), db: Session = Depends(get_db)):
    from models.benutzer import Benutzer

    kuerzel = kuerzel.strip().upper()
    user = db.query(Benutzer).filter(Benutzer.kuerzel == kuerzel).first()

    if not user or not user.check_passwort(passwort):
        return templates.TemplateResponse("pages/login.html", {
            "request": request,
            "error": "Ungueltiges Kuerzel oder Passwort.",
        })

    if not user.ist_aktiv:
        return templates.TemplateResponse("pages/login.html", {
            "request": request,
            "error": "Dieses Konto ist deaktiviert.",
        })

    user.letzter_login = datetime.now()
    db.commit()

    token = create_session_token(user.id)
    response = RedirectResponse(url="/", status_code=303)
    response.set_cookie(SESSION_COOKIE, token, httponly=True, samesite="lax")
    return response


@router.get("/logout")
async def logout():
    response = RedirectResponse(url="/login", status_code=303)
    response.delete_cookie(SESSION_COOKIE)
    return response
