from src.apis.version1.admin.login import login_for_token_cookie
from fastapi import APIRouter
from fastapi import HTTPException
from fastapi import Request
from fastapi.templating import Jinja2Templates
from src.webapps.auth.forms import LoginForm


templates = Jinja2Templates(directory="src/templates")
router = APIRouter(include_in_schema=False)


@router.get("/login/")
def login(request: Request):
    return templates.TemplateResponse("auth/login.html", {"request": request})


@router.post("/login/")
async def validate_login(request: Request):
    form = LoginForm(request)
    await form.load_data()
    if await form.is_valid():
        try:
            form.__dict__.update(msg="Login Successful :)")
            response = templates.TemplateResponse("auth/login.html", form.__dict__)
            login_for_token_cookie(response=response, form_data=form)
            return response
        except HTTPException:
            form.__dict__.update(msg="")
            errors = form.__dict__.get("errors")
            if errors:
                errors.append("Incorrect Email or Password")
            return templates.TemplateResponse("auth/login.html", form.__dict__)
    return templates.TemplateResponse("auth/login.html", form.__dict__)