from fastapi import APIRouter, Depends, Form, Request
from fastapi.responses import HTMLResponse, RedirectResponse
from sqlalchemy.orm import Session
from app.database import get_db
from app.models import User

router = APIRouter(prefix="/auth", tags=["auth"])

SESSION_COOKIE = "ft_session"


@router.get("/login", response_class=HTMLResponse)
def login_page(request: Request):
    template = request.app.state.templates.get_template("login.html")
    return HTMLResponse(template.render(request=request))


@router.post("/login")
def login(
    request: Request,
    username: str = Form(...),
    password: str = Form(...),
    db: Session = Depends(get_db),
):
    user = db.query(User).filter(User.username == username).first()
    if not user or not user.check_password(password):
        template = request.app.state.templates.get_template("login.html")
        return HTMLResponse(
            template.render(request=request, error="用户名或密码错误"),
            status_code=401,
        )

    resp = RedirectResponse("/contracts/", status_code=303)
    resp.set_cookie(SESSION_COOKIE, str(user.id), httponly=True)
    return resp


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