from .base import BaseEntity
from ..utils.utils import make_request, convert_dict_keys_to_snake_case
from ..utils.config import get_organization_id


class User(BaseEntity):
    def __init__(
        self,
        id: str = None,
        organization_id: str = None,
        phone_number_id: str = None,
        email: str = None,
        name: str = None,
        is_admin: bool = None,
        balance: float = None,
        created_at: str = None,
        updated_at: str = None,
        deleted_at: str = None,
        **kwargs,
    ):
        self.id = id
        self.organization_id = organization_id
        self.phone_number_id = phone_number_id
        self.email = email
        self.name = name
        self.is_admin = is_admin
        self.balance = balance
        self.created_at = created_at
        self.updated_at = updated_at
        self.deleted_at = deleted_at or None


def get_current_user(include_org_id=True) -> User:
    """Get the current authenticated user from the session.

    Args:
        include_org_id: If False, omits the organization-id header from the
            request so the API returns the user's real organization ID
            instead of the effective override.
    """
    response = make_request("/v1/auth/session", include_org_id=include_org_id)

    if response and "data" in response:
        data = convert_dict_keys_to_snake_case(response["data"])
        return User(**data)

    return None



def get_effective_organization_id() -> str:
    """Get the effective organization ID.

    Returns the organization ID from the config override if set,
    otherwise returns the organization ID from the current user's session.
    """
    # Check for config override first
    org_id = get_organization_id()
    if org_id:
        return org_id

    # Fall back to user's session
    user = get_current_user()
    if user and user.organization_id:
        return user.organization_id

    return None
