from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import text
from app.db.session import get_db
from app.services.auth_service import AuthService
from app.core.security import create_access_token
from app.schemas.auth import UserLiteRegister, Token, PasswordResetRequest

router = APIRouter()

@router.post("/register-lite", response_model=Token, status_code=201)
async def register_lite(user_in: UserLiteRegister, db: AsyncSession = Depends(get_db)):
    # Email csekkolás nyers SQL-el
    check = await db.execute(text("SELECT id FROM data.users WHERE email = :e"), {"e": user_in.email})
    if check.fetchone():
        raise HTTPException(status_code=400, detail="Ez az email cím már foglalt.")
    
    try:
        user = await AuthService.register_lite(db, user_in)
        token = create_access_token(data={"sub": str(user.id)})
        return {"access_token": token, "token_type": "bearer", "is_active": user.is_active}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Szerver hiba: {str(e)}")

@router.post("/login", response_model=Token)
async def login(form_data: OAuth2PasswordRequestForm = Depends(), db: AsyncSession = Depends(get_db)):
    user = await AuthService.authenticate(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=401, detail="Hibás e-mail vagy jelszó.")
    
    token = create_access_token(data={"sub": str(user.id)})
    return {"access_token": token, "token_type": "bearer", "is_active": user.is_active}

@router.post("/forgot-password")
async def forgot_password(req: PasswordResetRequest, db: AsyncSession = Depends(get_db)):
    await AuthService.initiate_password_reset(db, req.email)
    return {"message": "Helyreállítási folyamat elindítva."}

@router.get("/verify-email")
async def verify_email(token: str, db: AsyncSession = Depends(get_db)):
    """Ezt hívja meg a frontend, amikor a user a levélben a gombra kattint."""
    success = await AuthService.verify_email(db, token)
    if not success:
        raise HTTPException(status_code=400, detail="Érvénytelen vagy lejárt token.")
    return {"message": "Email sikeresen megerősítve! Most már elvégezheti a KYC regisztrációt (Step 2)."}