"""Authentication endpoints for JWT."""

from datetime import timedelta
from typing import Any

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm

from core.auth import (
    Token,
    User,
    create_access_token,
    get_current_active_user,
    verify_password,
    ACCESS_TOKEN_EXPIRE_MINUTES,
)

router = APIRouter(prefix="/auth", tags=["authentication"])


# TODO: Replace with actual database lookup
def get_user_from_db(username: str):
    """Fetch user from database."""
    # This is a mock implementation
    # Replace with actual database query
    fake_users_db = {
        "admin": {
            "username": "admin",
            "full_name": "Admin User",
            "email": "admin@example.com",
            "hashed_password": "$2b$12$...",  # bcrypt hash of "admin"
            "disabled": False,
        }
    }
    return fake_users_db.get(username)


@router.post("/token", response_model=Token)
async def login_for_access_token(
    form_data: OAuth2PasswordRequestForm = Depends(),
) -> Any:
    """
    OAuth2 compatible token login.

    Get an access token for future requests.
    """
    user = get_user_from_db(form_data.username)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )

    # TODO: Verify password against stored hash
    # if not verify_password(form_data.password, user["hashed_password"]):
    #     raise HTTPException(...)

    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    access_token = create_access_token(
        data={"sub": user["username"]}, expires_delta=access_token_expires
    )
    return {"access_token": access_token, "token_type": "bearer"}


@router.get("/me", response_model=User)
async def read_users_me(
    current_user: User = Depends(get_current_active_user),
) -> Any:
    """
    Get current user.

    Returns information about the currently authenticated user.
    """
    return current_user


@router.post("/register")
async def register_user(
    username: str,
    password: str,
    email: str,
) -> Any:
    """
    Register a new user.

    Creates a new user account.
    """
    # TODO: Implement user registration
    # 1. Check if user already exists
    # 2. Hash password
    # 3. Save to database
    return {"message": "User registered successfully", "username": username}
