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="/auth", tags=["Auth"])
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()

# @router.post("/register")
# def register(user: UserCreate, db: Session = Depends(get_db)):
#     hashed_pw = pwd_context.hash(user.password)
#     new_user = User(email=user.email, password=hashed_pw)
#     db.add(new_user)
#     db.commit()
#     db.refresh(new_user)
#     return {"message": "User registered successfully"}

@router.post("/login")
def login(user: UserLogin, db: Session = Depends(get_db)):
    db_user = db.query(User).filter(User.email == user.email).first()
    if not db_user or not pwd_context.verify(user.password, db_user.password):
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
    
    access_token = jwt.encode({"user_id":db_user.id, "user_email": db_user.email, "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1)}, SECRET_KEY, algorithm=ALGORITHM)
    return {"status": "true", "access_token": access_token, "token_type": "bearer"}

# class UserCreate(BaseModel):
#     username: str
#     firstname_deg: Optional[str] = None
#     firstname: str
#     email: str
#     password: str
#     telephone: Optional[str] = None
#     user_role_group: Optional[str] = None
#     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:
#         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,
#         firstname_deg=user.firstname_deg,
#         firstname=user.firstname,
#         email=user.email,
#         password=hashed_pw,
#         telephone=user.telephone,
#         user_role_group=user.user_role_group,
#         speciality=user.speciality
#     )

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

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



# @router.post("/login")
# def login(user: UserLogin, db: Session = Depends(get_db)):
#     db_user = db.query(User).filter(User.email == user.email).first()
#     if not db_user or not pwd_context.verify(user.password, db_user.password):
#         raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid credentials")
    
#     access_token = jwt.encode({"user_id":db_user.id, "user_email": db_user.email, "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1)}, SECRET_KEY, algorithm=ALGORITHM)
#     return {"status": "true", "access_token": access_token, "token_type": "bearer"}
