# /opt/docker/dev/service_finder/backend/app/api/v1/endpoints/auth.py
from fastapi import APIRouter, Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from app.db.session import get_db
from app.services.auth_service import AuthService
from app.core.security import create_tokens, DEFAULT_RANK_MAP
from app.core.config import settings
from app.schemas.auth import UserLiteRegister, Token, UserKYCComplete
from app.api.deps import get_current_user
from app.models.identity import User # JAVÍTVA: Új központi modell
from pydantic import BaseModel, Field

router = APIRouter()

@router.post("/register", status_code=status.HTTP_201_CREATED)
async def register(user_in: UserLiteRegister, db: AsyncSession = Depends(get_db)):
    """
    Regisztráció (Lite fázis) - új felhasználó létrehozása.
    """
    user = await AuthService.register_lite(db, user_in)
    return {
        "status": "success",
        "message": "Regisztráció sikeres. Aktivációs e-mail elküldve.",
        "user_id": user.id,
        "email": user.email
    }

@router.post("/login", response_model=Token)
async def login(db: AsyncSession = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()):
    user = await AuthService.authenticate(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=401, detail="Hibás adatok.")
    
    ranks = await settings.get_db_setting(db, "rbac_rank_matrix", default=DEFAULT_RANK_MAP)
    role_name = user.role.value if hasattr(user.role, 'value') else str(user.role)
    role_key = role_name.upper()  # A DEFAULT_RANK_MAP nagybetűs kulcsokat vár

    token_data = {
        "sub": str(user.id),
        "role": role_name,
        "rank": ranks.get(role_key, 10),
        "scope_level": user.scope_level or "individual",
        "scope_id": str(user.scope_id) if user.scope_id else str(user.id)
    }
    
    access, refresh = create_tokens(data=token_data)
    return {"access_token": access, "refresh_token": refresh, "token_type": "bearer", "is_active": user.is_active}

class VerifyEmailRequest(BaseModel):
    token: str = Field(..., description="Email verification token (UUID)")

@router.post("/verify-email")
async def verify_email(request: VerifyEmailRequest, db: AsyncSession = Depends(get_db)):
    """
    Email megerősítés token alapján.
    """
    success = await AuthService.verify_email(db, request.token)
    if not success:
        raise HTTPException(status_code=400, detail="Érvénytelen vagy lejárt token.")
    return {"status": "success", "message": "Email sikeresen megerősítve."}

@router.post("/complete-kyc")
async def complete_kyc(kyc_in: UserKYCComplete, db: AsyncSession = Depends(get_db), current_user: User = Depends(get_current_user)):
    user = await AuthService.complete_kyc(db, current_user.id, kyc_in)
    if not user:
        raise HTTPException(status_code=404, detail="User nem található.")
    return {"status": "success", "message": "Fiók aktiválva."}

@router.get("/me")
async def get_current_user_profile(current_user: User = Depends(get_current_user)):
    """
    Return current user profile (alias for /users/me).
    """
    from app.schemas.user import UserResponse
    return UserResponse.model_validate(current_user)