from fastapi import APIRouter, Depends, HTTPException, status, Header
from sqlalchemy.orm import Session
from app.database.connection import SessionLocal
from app.models.user import User
from passlib.context import CryptContext
from pydantic import BaseModel
from typing import Optional

router = APIRouter(prefix="", tags=["User"])
pwd_context = CryptContext(schemes=["argon2"], deprecated="auto")  # same as create_user

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# Request body model
class ChangePasswordRequest(BaseModel):
    current_password: str
    new_password: str
    confirm_password: str


@router.put("/change_password/{user_id}")
def change_password(
    user_id: int,
    body: ChangePasswordRequest,
    db: Session = Depends(get_db),
    access_token: Optional[str] = Header(None)
):
    # Check if token is present (optional auth validation)
    if not access_token:
        return {"status": "false", "message": "Access token missing"}

    # Find the user
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        return {"status": "false", "message": "User not found"}

    # Verify current password
    if not pwd_context.verify(body.current_password, user.password):
        return {"status": "false", "message": "Current password is incorrect"}

    # Check if new and confirm match
    if body.new_password != body.confirm_password:
        return {"status": "false", "message": "New passwords do not match"}

    # Hash and update password
    user.password = pwd_context.hash(body.new_password)
    db.commit()

    return {"status": "true", "message": "Password changed successfully"}
