from fastapi import APIRouter, Request, Form, Depends
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from app.auth import get_current_user, verify_password, hash_password
from app.database import db

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

@router.get("/perfil", response_class=HTMLResponse)
async def perfil(request: Request, user=Depends(get_current_user)):
    return templates.TemplateResponse("perfil.html", {
        "request": request,
        "user": user
    })

@router.post("/perfil/cambiar-password")
async def cambiar_password_usuario(
    request: Request,
    new_password: str = Form(...),
    confirm_password: str = Form(...),
    user=Depends(get_current_user)
):
    if new_password != confirm_password:
        return templates.TemplateResponse("perfil.html", {
            "request": request,
            "user": user,
            "error": "La nueva contraseña y su confirmación no coinciden."
        })

    await db.users.update_one(
        {"username": user.username},
        {"$set": {"password": hash_password(new_password)}}
    )

    return templates.TemplateResponse("perfil.html", {
        "request": request,
        "user": user,
        "success": "Contraseña actualizada correctamente."
    })
