"""Referral service for managing user invitations."""

from config import settings
from database import (
    get_user_by_referral_code,
    get_referral_by_invited,
    create_referral,
    update_user_score,
)


async def process_referral(new_user_telegram_id: int, referral_code: str) -> bool:
    """Process referral when a new user registers.

    Returns True if referral was processed successfully.
    """
    # Check if user already has been referred
    from database import get_user_by_telegram_id
    new_user = await get_user_by_telegram_id(new_user_telegram_id)
    if not new_user:
        return False

    # Check if referral already exists
    existing_referral = await get_referral_by_invited(new_user["id"])
    if existing_referral:
        return False

    # Find inviter by referral code
    inviter = await get_user_by_referral_code(referral_code)
    if not inviter:
        return False

    # Inviter and invited are the same person
    if inviter["telegram_id"] == new_user_telegram_id:
        return False

    # Create referral record
    await create_referral(inviter["id"], new_user["id"])

    # Add score to inviter
    await update_user_score(inviter["id"], settings.SCORE_REFERRAL_SUCCESS)

    return True


async def get_referral_stats(inviter_id: int) -> dict:
    """Get referral statistics for an inviter."""
    from database import get_referral_count_for_user

    count = await get_referral_count_for_user(inviter_id)
    return {"total_referrals": count, "score_earned": count * settings.SCORE_REFERRAL_SUCCESS}