-- name: CreateReferral :one
INSERT INTO referrals (
    referral_code,
    referrer_id,
    status,
    reward_amount,
    expires_at
) VALUES (
    $1, $2, $3, $4, $5
) RETURNING *;

-- name: GetReferralByCode :one
SELECT * FROM referrals
WHERE referral_code = $1;

-- name: UpdateReferral :one
UPDATE referrals
SET
    referred_id = $2,
    status = $3,
    updated_at = CURRENT_TIMESTAMP
WHERE id = $1
RETURNING *;

-- name: UpdateReferralCode :exec
UPDATE users
SET
    referral_code = $2,
    updated_at = CURRENT_TIMESTAMP
WHERE id = $1;

-- name: GetReferralStats :one
SELECT
    COUNT(*) as total_referrals,
    COUNT(CASE WHEN status = 'COMPLETED' THEN 1 END) as completed_referrals,
    COALESCE(SUM(reward_amount), 0) as total_reward_earned,
    COALESCE(SUM(CASE WHEN status = 'PENDING' THEN reward_amount END), 0) as pending_rewards
FROM referrals
WHERE referrer_id = $1;

-- name: GetReferralSettings :one
SELECT * FROM referral_settings
WHERE id = 'default'
LIMIT 1;

-- name: UpdateReferralSettings :one
UPDATE referral_settings
SET
    referral_reward_amount = $2,
    cashback_percentage = $3,
    bet_referral_bonus_percentage= $4,
    max_referrals = $5,
    expires_after_days = $6,
    updated_by = $7,
    updated_at = CURRENT_TIMESTAMP
WHERE id = $1
RETURNING *;

-- name: CreateReferralSettings :one
INSERT INTO referral_settings (
    referral_reward_amount,
    cashback_percentage,
    max_referrals,
    bet_referral_bonus_percentage,
    expires_after_days,
    updated_by
) VALUES (
    $1, $2, $3, $4, $5, $6
) RETURNING *;

-- name: GetReferralByReferredID :one
SELECT * FROM referrals WHERE referred_id = $1 LIMIT 1;
