-- Referral System Tables

CREATE TABLE IF NOT EXISTS referral_codes (
    id CHAR(36) PRIMARY KEY,
    user_id CHAR(36) NOT NULL,
    tenant_id CHAR(36) NOT NULL,
    code VARCHAR(20) NOT NULL UNIQUE,
    is_active TINYINT(1) DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_user (user_id),
    INDEX idx_code (code),
    FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

CREATE TABLE IF NOT EXISTS referrals (
    id CHAR(36) PRIMARY KEY,
    referrer_id CHAR(36) NOT NULL,
    referred_id CHAR(36) NULL,
    referral_code VARCHAR(20) NOT NULL,
    status ENUM('clicked', 'registered', 'subscribed') DEFAULT 'clicked',
    reward_claimed TINYINT(1) DEFAULT 0,
    reward_type VARCHAR(50) NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    converted_at TIMESTAMP NULL,
    INDEX idx_referrer (referrer_id),
    INDEX idx_code (referral_code),
    FOREIGN KEY (referrer_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
