-- 019: Refund records (clearing-service)
CREATE TABLE IF NOT EXISTS refunds (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id UUID NOT NULL REFERENCES users(id),
    coupon_id UUID NOT NULL REFERENCES coupons(id),
    order_id UUID REFERENCES orders(id),
    refund_type VARCHAR(20) NOT NULL CHECK (refund_type IN ('primary', 'secondary')),
    amount NUMERIC(12,2) NOT NULL,
    fee_refunded BOOLEAN NOT NULL DEFAULT false,
    reason VARCHAR(500),
    status VARCHAR(20) NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected', 'completed', 'failed')),
    requires_arbitration BOOLEAN NOT NULL DEFAULT false,
    processed_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_refunds_user_id ON refunds(user_id);
CREATE INDEX idx_refunds_coupon_id ON refunds(coupon_id);
CREATE INDEX idx_refunds_status ON refunds(status);
