from fastapi import APIRouter, HTTPException, Depends, status
from models.user import UserCreate, UserLogin, UserOut, TokenData
from utils.auth import hash_password, verify_password, create_access_token
from database import db
from datetime import timedelta
from utils.dependencies import get_current_user

router = APIRouter()

@router.post("/register", response_model=UserOut)
async def register(user: UserCreate, current_user: dict = Depends(get_current_user)):
    if current_user["role"] != "admin":
        raise HTTPException(status_code=403, detail="Only admin can register users.")

    if user.role == "admin" and current_user["role"] != "admin":
        raise HTTPException(status_code=403, detail="Only an admin can create another admin.")

    normalized_email = user.email.strip().lower()
    existing = await db.users.find_one({"email": normalized_email})
    if existing:
        raise HTTPException(status_code=400, detail="User already exists.")

    hashed_pw = hash_password(user.password)

    new_user = {
    "email": normalized_email,
    "password": hashed_pw,
    "role": user.role
    }
    
    await db.users.insert_one(new_user)

    return {"email": user.email, "role": user.role}

@router.post("/login")
async def login(credentials: UserLogin):
    normalized_email = credentials.email.strip().lower()
    user = await db.users.find_one({"email": normalized_email})
    if not user:
        raise HTTPException(status_code=401, detail="Invalid credentials.")

    if not verify_password(credentials.password, user["password"]):
        raise HTTPException(status_code=401, detail="Invalid credentials.")

    token = create_access_token(
        data={"email": user["email"], "role": user["role"]},
        expires_delta=timedelta(minutes=60)
    )

    return {"access_token": token, "token_type": "bearer"}

@router.get("/me")
async def read_users_me(current_user: TokenData = Depends(get_current_user)):
    return {"email": current_user.email, "role": current_user.role}
