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"])
pwd_context = CryptContext(schemes=["argon2"], deprecated="auto")
SECRET_KEY = "YOUR_SECRET_KEY"
ALGORITHM = "HS256"

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

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

@router.post("/create_user")
def create_user(
    user: UserCreate,
    db: Session = Depends(get_db),
    access_token: Optional[str] = Header(None)
):
    
    if not access_token:
        return {"status":"false", "message": "Access token missing"}
        # raise HTTPException(status_code=401, detail="Access token missing")
    # try:
    #     payload = jwt.decode(access_token, SECRET_KEY, algorithms=[ALGORITHM])
    #     user_id = payload.get("sub")
    #     if user_id is None:
    #         raise HTTPException(status_code=401, detail="Invalid token")
    # except jwt.ExpiredSignatureError:
    #     raise HTTPException(status_code=401, detail="Token expired")
    # except jwt.InvalidTokenError:
    #     raise HTTPException(status_code=401, detail="Invalid token")
    
    # existing_user = db.query(User).filter(User.email == user.email).first()
    # if existing_user:
    #     raise HTTPException(status_code=400, detail="Email already registered")
    
    hashed_pw = pwd_context.hash(user.password)

    new_user = User(
        username = user.username,
        title = user.title,
        first_name = user.first_name,
        last_name = user.last_name,
        email = user.email,
        telephone_number = user.telephone_number,
        role_id = user.role_id,
        password = hashed_pw,
        speciality = user.speciality,
    )

    db.add(new_user)
    db.commit()
    db.refresh(new_user)

    return {"status":"true","message": "User created successfully", "user_id": new_user.id}