-- Coupons, promotions, referral, and bonus credits (Task 6)
-- Implements coupon redemption, promotions, referral tracking

BEGIN;

-- Coupons table for discount codes
CREATE TABLE ai_coupons (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    code VARCHAR(100) UNIQUE NOT NULL,
    name VARCHAR(200) NOT NULL,
    description TEXT,
    
    -- Discount configuration
    discount_type VARCHAR(20) NOT NULL CHECK (discount_type IN ('percentage', 'fixed_amount')),
    discount_value NUMERIC(10, 2) NOT NULL CHECK (discount_value >= 0),
    
    -- Applicability
    applicable_package_ids UUID[] DEFAULT '{}',
    applicable_plan_codes TEXT[] DEFAULT '{}',
    min_purchase_amount NUMERIC(12, 2),
    max_discount_amount NUMERIC(12, 2),
    
    -- Limits
    max_redemptions INT NOT NULL DEFAULT 1,
    redemptions_used INT NOT NULL DEFAULT 0,
    max_redemptions_per_user INT DEFAULT 1,
    
    -- Validity
    valid_from TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    valid_until TIMESTAMPTZ,
    
    -- Status
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    
    -- Audit
    created_by UUID REFERENCES users(id),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Coupon redemptions (tracks who used which coupon)
CREATE TABLE ai_coupon_redemptions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    coupon_id UUID NOT NULL REFERENCES ai_coupons(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    order_id UUID, -- Reference to ai_credit_orders
    credits_purchased INT NOT NULL,
    discount_applied NUMERIC(12, 2) NOT NULL,
    final_amount_paid NUMERIC(12, 2) NOT NULL,
    redeemed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    
    UNIQUE(coupon_id, user_id)
);

-- Promotions table for automatic bonuses
CREATE TABLE ai_promotions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    name VARCHAR(200) NOT NULL,
    description TEXT,
    
    -- Trigger conditions
    trigger_type VARCHAR(50) NOT NULL CHECK (trigger_type IN ('signup', 'first_purchase', 'referral', 'milestone', 'manual')),
    trigger_condition JSONB DEFAULT '{}', -- e.g., {"min_purchase": 100, "referrer_bonus": 50}
    
    -- Reward
    bonus_credits INT NOT NULL CHECK (bonus_credits > 0),
    bonus_expires_after_days INT, -- NULL means no expiry
    
    -- Applicability
    applicable_plan_codes TEXT[] DEFAULT '{}',
    applicable_user_types TEXT[] DEFAULT '{}', -- e.g., ['NEW_USER', 'REFERRER']
    
    -- Limits
    max_grants INT,
    grants_used INT NOT NULL DEFAULT 0,
    max_grants_per_user INT DEFAULT 1,
    
    -- Validity
    valid_from TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    valid_until TIMESTAMPTZ,
    
    -- Status
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    
    -- Audit
    created_by UUID REFERENCES users(id),
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Promotion grants (tracks who received which promotion)
CREATE TABLE ai_promotion_grants (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    promotion_id UUID NOT NULL REFERENCES ai_promotions(id) ON DELETE CASCADE,
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    ledger_entry_id UUID REFERENCES ai_credit_ledger(id), -- Link to the bonus credit ledger entry
    bonus_credits INT NOT NULL,
    expires_at TIMESTAMPTZ,
    granted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    
    UNIQUE(promotion_id, user_id)
);

-- Bonus credits ledger reference
-- This extends ai_credit_ledger with source tracking for bonus credits
CREATE TABLE ai_bonus_credits (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    source_type VARCHAR(30) NOT NULL CHECK (source_type IN ('promotion', 'coupon_bonus', 'referral', 'manual', 'signup_bonus')),
    source_reference_id UUID, -- References ai_promotions, ai_coupon_redemptions, etc.
    credits INT NOT NULL CHECK (credits > 0),
    credits_used INT NOT NULL DEFAULT 0 CHECK (credits_used >= 0 AND credits_used <= credits),
    expires_at TIMESTAMPTZ,
    ledger_entry_id UUID REFERENCES ai_credit_ledger(id),
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Referral tracking
CREATE TABLE ai_referrals (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    referrer_user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
    referred_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
    referral_code VARCHAR(100) NOT NULL UNIQUE,
    
    -- Status
    status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'converted', 'expired')),
    
    -- Rewards (granted when referred user completes first purchase)
    referrer_bonus_credits INT,
    referred_bonus_credits INT,
    
    -- Conversion tracking
    converted_at TIMESTAMPTZ,
    first_purchase_order_id UUID REFERENCES ai_credit_orders(id),
    
    -- Expiry
    expires_at TIMESTAMPTZ NOT NULL DEFAULT (NOW() + INTERVAL '30 days'),
    
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Indexes for performance
CREATE INDEX idx_ai_coupons_code ON ai_coupons(code) WHERE is_active = TRUE;
CREATE INDEX idx_ai_coupons_valid ON ai_coupons(valid_from, valid_until) WHERE is_active = TRUE;
CREATE INDEX idx_ai_coupon_redemptions_user ON ai_coupon_redemptions(user_id);
CREATE INDEX idx_ai_coupon_redemptions_coupon ON ai_coupon_redemptions(coupon_id);

CREATE INDEX idx_ai_promotions_trigger ON ai_promotions(trigger_type) WHERE is_active = TRUE;
CREATE INDEX idx_ai_promotions_valid ON ai_promotions(valid_from, valid_until) WHERE is_active = TRUE;
CREATE INDEX idx_ai_promotion_grants_user ON ai_promotion_grants(user_id);

CREATE INDEX idx_ai_bonus_credits_user ON ai_bonus_credits(user_id) WHERE is_active = TRUE;
CREATE INDEX idx_ai_bonus_credits_expires ON ai_bonus_credits(expires_at) WHERE expires_at IS NOT NULL AND is_active = TRUE;

CREATE INDEX idx_ai_referrals_referrer ON ai_referrals(referrer_user_id);
CREATE INDEX idx_ai_referrals_code ON ai_referrals(referral_code);
CREATE INDEX idx_ai_referrals_referred ON ai_referrals(referred_user_id) WHERE referred_user_id IS NOT NULL;

COMMIT;
