CREATE TYPE ReferralStatus AS ENUM ('PENDING', 'COMPLETED', 'EXPIRED', 'CANCELLED');
CREATE TABLE IF NOT EXISTS referral_settings (
    id BIGSERIAL PRIMARY KEY,
    referral_reward_amount DECIMAL(15, 2) NOT NULL DEFAULT 0.00,
    cashback_percentage DECIMAL(5, 2) NOT NULL DEFAULT 0.00,
    bet_referral_bonus_percentage NUMERIC DEFAULT 5.0,
    max_referrals INTEGER NOT NULL DEFAULT 0,
    expires_after_days INTEGER NOT NULL DEFAULT 30,
    updated_by VARCHAR(255) NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    version INTEGER NOT NULL DEFAULT 0,
    CONSTRAINT referral_reward_amount_positive CHECK (referral_reward_amount >= 0),
    CONSTRAINT cashback_percentage_range CHECK (
        cashback_percentage >= 0
        AND cashback_percentage <= 100
    )
);
CREATE TABLE IF NOT EXISTS referrals (
    id BIGSERIAL PRIMARY KEY,
    referral_code VARCHAR(10) NOT NULL UNIQUE,
    -- referrer_id VARCHAR(255) NOT NULL,
    -- referred_id VARCHAR(255) UNIQUE,
    status ReferralStatus NOT NULL DEFAULT 'PENDING',
    reward_amount DECIMAL(15, 2) NOT NULL DEFAULT 0.00,
    cashback_amount DECIMAL(15, 2) NOT NULL DEFAULT 0.00,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMPTZ NOT NULL,
    -- FOREIGN KEY (referrer_id) REFERENCES users (id),
    -- FOREIGN KEY (referred_id) REFERENCES users (id),
    CONSTRAINT reward_amount_positive CHECK (reward_amount >= 0),
    CONSTRAINT cashback_amount_positive CHECK (cashback_amount >= 0)
);
CREATE INDEX idx_referrals_referral_code ON referrals (referral_code);
-- CREATE INDEX idx_referrals_referrer_id ON referrals (referrer_id);
CREATE INDEX idx_referrals_status ON referrals (status);
ALTER TABLE users
ADD COLUMN IF NOT EXISTS referral_code VARCHAR(10) UNIQUE,
    ADD COLUMN IF NOT EXISTS referred_by VARCHAR(10);
-- Modify wallet table to track bonus money separately
ALTER TABLE wallets
ADD COLUMN IF NOT EXISTS bonus_balance DECIMAL(15, 2) NOT NULL DEFAULT 0.00,
    ADD COLUMN IF NOT EXISTS cash_balance DECIMAL(15, 2) NOT NULL DEFAULT 0.00,
    ADD CONSTRAINT bonus_balance_positive CHECK (bonus_balance >= 0),
    ADD CONSTRAINT cash_balance_positive CHECK (cash_balance >= 0);