from fastapi import APIRouter, Depends, HTTPException, Request, status, Body
from sqlalchemy.ext.asyncio import AsyncSession
from app.db.session import get_db
from app.schemas.auth import UserRegister, Token, UserLogin
from app.services.auth_service import AuthService
from app.core.security import create_access_token

router = APIRouter()

@router.post("/register", response_model=Token, status_code=status.HTTP_201_CREATED)
async def register(
    request: Request,
    user_in: UserRegister = Body(...), 
    db: AsyncSession = Depends(get_db)
):
    """Atomi Regisztráció KYC adatokkal és privát flotta létrehozásával."""
    # 1. Elérhetőség
    is_available = await AuthService.check_email_availability(db, user_in.email)
    if not is_available:
        raise HTTPException(status_code=400, detail="Az e-mail cím már foglalt.")

    # 2. Végrehajtás
    user = await AuthService.register_new_user(
        db=db, 
        user_in=user_in, 
        ip_address=request.client.host
    )
    
    # 3. Token generálás
    token_data = {"sub": str(user.id), "email": user.email}
    access_token = create_access_token(data=token_data)
    
    return {"access_token": access_token, "token_type": "bearer"}

@router.post("/login", response_model=Token)
async def login(user_in: UserLogin = Body(...), db: AsyncSession = Depends(get_db)):
    # TODO: Implement login logic
    raise HTTPException(status_code=501, detail="Login not yet implemented")