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 app.schemas.user_schema import UserCreate, UserLogin
from passlib.context import CryptContext
from jose import JWTError, jwt
import datetime
from pydantic import BaseModel
from typing import Optional

router = APIRouter(prefix="", tags=["User"])

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

class UserEdit(BaseModel):
    username: Optional[str] = None
    title: Optional[str] = None
    first_name: Optional[str] = None
    last_name: Optional[str] = None
    telephone_number: Optional[str] = None
    role_id: Optional[str] = None
    speciality: Optional[str] = None

@router.put("/edit_user/{user_id}")
def edit_user(
    user_id: int,
    user: UserEdit,
    db: Session = Depends(get_db),
    access_token: Optional[str] = Header(None)
):
    if not access_token:
        return {"status":"false", "message": "Access token missing"}
    
    existing_user = db.query(User).filter(User.id == user_id).first()
    if not existing_user:
        return {"status":"false", "message": "User not found"}

    # Update only provided fields
    user_update_data = user.dict(exclude_unset=True)
    for field, value in user_update_data.items():setattr(existing_user, field, value)

    db.commit()
    db.refresh(existing_user)

    return {"status":"true","message": "User updated successfully", "user_id": existing_user.id}