from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from datetime import timedelta
from src.config import auth_settings
from .service import AuthService, UserCreate, Token

router = APIRouter()
auth_service = AuthService()

@router.post("/register", response_model=dict)
def register_user(user: UserCreate):
    existing_user = auth_service.get_user_by_username(user.username)
    if existing_user:
        raise HTTPException(status_code=400, detail="Username already registered")
    
    user_id = auth_service.create_user(user)
    return {"message": "User created successfully", "user_id": user_id}

@router.post("/login", response_model=Token)
def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
    user = auth_service.get_user_by_username(form_data.username)
    if not user or not auth_service.verify_password(form_data.password, user["password_hash"]):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    access_token_expires = timedelta(minutes=auth_settings.access_token_expire_minutes)
    access_token = auth_service.create_access_token(
        subject=str(user["_id"]), expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}
