from fastapi import APIRouter, Form, Request
from fastapi.responses import RedirectResponse, HTMLResponse
from fastapi.templating import Jinja2Templates
from app.auth import authenticate_user, create_access_token
from starlette.status import HTTP_302_FOUND
from urllib.parse import urlparse


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


def _sanitize_next_path(next_path: str | None, default: str = "/dashboard") -> str:
    candidate = str(next_path or "").strip()
    if not candidate:
        return default

    parsed = urlparse(candidate)
    if parsed.scheme or parsed.netloc:
        return default
    if not candidate.startswith("/") or candidate.startswith("//"):
        return default
    if "\\" in candidate:
        return default
    if candidate.startswith("/login"):
        return default
    return candidate


@router.get("/login", response_class=HTMLResponse)
async def show_login_form(request: Request):
    next_path = _sanitize_next_path(request.query_params.get("next"), default="/dashboard")
    access_token = request.cookies.get("access_token")

    if access_token:
        try:
            from app.auth import get_current_user
            user = await get_current_user(access_token=access_token)
            if user:
                return RedirectResponse(url=next_path, status_code=302)
        except:
            pass

    return templates.TemplateResponse(
        "login.html",
        {"request": request, "next_path": next_path},
    )

@router.post("/login")
async def login_post(
    request: Request,
    username: str = Form(...),
    password: str = Form(...),
    next_path: str = Form(default="/dashboard", alias="next"),
):
    safe_next = _sanitize_next_path(next_path, default="/dashboard")
    user = await authenticate_user(username, password)
    if not user:
        # Vuelve a mostrar el login con error
        return templates.TemplateResponse(
            "login.html",
            {
                "request": request,
                "error": "Credenciales inválidas",
                "next_path": safe_next,
            },
        )

    token = create_access_token({"sub": user.username})
    response = RedirectResponse(url=safe_next, status_code=302)
    response.set_cookie(key="access_token", value=f"Bearer {token}", httponly=True)
    return response


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