-- name: CreateReferralCode :one
INSERT INTO referral_codes (
              referral_code,
              referrer_id,
              company_id,
              number_of_referrals,
              reward_amount
       )
VALUES ($1, $2, $3, $4, $5)
RETURNING *;
-- name: CreateUserReferral :one
INSERT INTO user_referrals (referred_id, referral_code_id)
VALUES ($1, $2)
RETURNING *;
-- name: GetReferralCodeByUser :many
SELECt *
FROM referral_codes
WHERE referrer_id = $1;
-- name: GetReferralCode :one
SELECT *
FROM referral_codes
WHERE referral_code = $1;
-- name: UpdateReferralCode :exec
UPDATE referral_codes
SET is_active = $2,
       referral_code = $3,
       number_of_referrals = $4,
       reward_amount = $5,
       updated_at = CURRENT_TIMESTAMP
WHERE id = $1;
-- name: GetReferralStats :one
SELECT COUNT(*) AS total_referrals,
       SUM(reward_amount) AS total_reward_earned
FROM user_referrals
       JOIN referral_codes ON referral_codes.id == referral_code_id
WHERE referrer_id = $1
       AND company_id = $2;
-- name: GetUserReferral :one
SELECT *
FROM user_referrals
WHERE referred_id = $1;
-- name: GetUserReferralsByCode :many
SELECT user_referrals.*
FROM user_referrals
       JOIN referral_codes ON referral_codes.id == referral_code_id
WHERE referral_code = $1;
-- name: GetUserReferralsCount :one
SELECT COUNT(*)
FROM user_referrals
       JOIN referral_codes ON referral_codes.id == referral_code_id
WHERE referrer_id = $1;