from fastapi import HTTPException, Depends, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
import jwt

from app.core.config import settings
from app.db.database import get_db

security = HTTPBearer()


def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)):
    """Middleware para validar JWT y retornar usuario actual."""
    token = credentials.credentials
    try:
        payload = jwt.decode(
            token,
            settings.secret_key,
            algorithms=[settings.algorithm]
        )
        user_id = payload.get("sub")
        if user_id is None:
            raise HTTPException(status_code=401, detail="Invalid token")

        # Obtener usuario de Supabase
        db = get_db()
        try:
            result = db.table("users").select("id, email, phone").eq("id", user_id).execute()
            if not result.data:
                raise HTTPException(status_code=401, detail="User not found")

            user = result.data[0]
            return {
                "id": user["id"],
                "email": user["email"],
                "phone": user["phone"]
            }
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"DB error: {str(e)}")

    except jwt.ExpiredSignatureError:
        raise HTTPException(status_code=401, detail="Token expired")
    except jwt.InvalidTokenError:
        raise HTTPException(status_code=401, detail="Invalid token")
