from telegram import Update
from telegram.ext import ContextTypes
from database.db import DB
from utils.helpers import referral_link, money
from utils.decorators import anti_flood

@anti_flood
async def referrals(update: Update, context: ContextTypes.DEFAULT_TYPE):
    uid = update.effective_user.id
    link = referral_link(uid)
    total = (await DB.fetchone("SELECT COUNT(*) AS c FROM users WHERE referred_by=?", (uid,)))["c"]
    active = (await DB.fetchone("SELECT COUNT(*) AS c FROM users WHERE referred_by=? AND is_active=1", (uid,)))["c"]
    qualified = (await DB.fetchone(
        "SELECT COUNT(*) AS c FROM referral_rewards WHERE referrer_id=? AND reward_type='purchase'",
        (uid,)))["c"]
    earnings = (await DB.fetchone(
        "SELECT COALESCE(SUM(amount),0) AS s FROM referral_rewards WHERE referrer_id=?",
        (uid,)))["s"]
    bal = (await DB.fetchone("SELECT referral_earnings FROM users WHERE user_id=?", (uid,)))["referral_earnings"]
    text = (
        "🎁 <b>Referral Program</b>\n\n"
        "Invite your friends and earn real cash rewards! 💸\n\n"
        f"🔗 <b>Your invite link:</b>\n<code>{link}</code>\n\n"
        f"👥 Total Referrals: <b>{total}</b>\n"
        f"✅ Active Referrals: <b>{active}</b>\n"
        f"💎 Qualified (purchased): <b>{qualified}</b>\n"
        f"💰 Total Earnings: <b>{money(earnings)}</b>\n"
        f"💼 Available in Wallet: <b>{money(bal)}</b>\n\n"
        "💎 <b>How it works:</b>\n"
        "• Earn <b>$0.40</b> for every <b>$5</b> your referral spends on the bot.\n"
        "• Rewards are auto-credited to your wallet.\n"
        "• You'll get a notification each time a reward is earned. 🔔"
    )
    await update.message.reply_html(text, disable_web_page_preview=True)
