-- AI credit coupon tables, extracted from the skipped
-- 20260706300000_ai_coupons_promotions.up.sql.skip which could not be
-- enabled because it referenced ai_credit_orders before that table
-- existed (it ran before 20260814000000 chronologically).
--
-- Only the tables actually used by apps/payments/src/ai_credits.rs are
-- created here (ai_coupons + ai_coupon_redemptions). The broader
-- promotions/referral tables from the original skip file are deferred.

BEGIN;

CREATE TABLE IF NOT EXISTS 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 '{}',
    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()
);

CREATE TABLE IF NOT EXISTS 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 REFERENCES ai_credit_orders(id),
    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)
);

CREATE INDEX IF NOT EXISTS idx_ai_coupons_code ON ai_coupons(code) WHERE is_active = TRUE;
CREATE INDEX IF NOT EXISTS idx_ai_coupons_valid ON ai_coupons(valid_from, valid_until) WHERE is_active = TRUE;
CREATE INDEX IF NOT EXISTS idx_ai_coupon_redemptions_user ON ai_coupon_redemptions(user_id);
CREATE INDEX IF NOT EXISTS idx_ai_coupon_redemptions_coupon ON ai_coupon_redemptions(coupon_id);

COMMIT;
