CREATE TABLE disputes (
                          id BIGINT PRIMARY KEY,
                          order_id BIGINT NOT NULL UNIQUE,
                          initiator_id BIGINT NOT NULL,
                          initiator_name VARCHAR(100) NOT NULL,
                          respondent_id BIGINT NOT NULL,
                          reason TEXT NOT NULL,
                          evidence TEXT[] DEFAULT ARRAY[]::TEXT[],
                          status VARCHAR(20) NOT NULL DEFAULT 'open',
                          result VARCHAR(30),
                          respondent_reason TEXT,
                          respondent_evidence TEXT[] DEFAULT ARRAY[]::TEXT[],
                          appeal_reason TEXT,
                          appealed_at TIMESTAMPTZ,
                          resolved_by BIGINT,
                          resolved_at TIMESTAMPTZ,
                          search_text TEXT GENERATED ALWAYS AS (
                              initiator_name || ' ' || reason || ' ' || coalesce(respondent_reason, '') || ' ' || coalesce(appeal_reason, '')
                              ) STORED,
                          created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
                          updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),

                          CONSTRAINT chk_dispute_status CHECK (status IN ('open', 'reviewing', 'resolved', 'appealed')),
                          CONSTRAINT chk_dispute_result CHECK (result IS NULL OR result IN ('full_refund', 'full_payment', 'partial_refund'))
);

-- 基础索引
CREATE INDEX idx_disputes_order ON disputes(order_id);
CREATE INDEX idx_disputes_status ON disputes(status, created_at DESC);
CREATE INDEX idx_disputes_initiator ON disputes(initiator_id);

-- 三元组索引用于争议内容搜索
CREATE INDEX idx_disputes_search_trgm ON disputes USING gin(search_text gin_trgm_ops);

-- 复合索引优化状态查询
CREATE INDEX idx_disputes_status_created ON disputes(status, created_at DESC);

-- 参与者索引
CREATE INDEX idx_disputes_initiator_status ON disputes(initiator_id, status, created_at DESC);
CREATE INDEX idx_disputes_respondent_status ON disputes(respondent_id, status, created_at DESC);

-- 数组索引优化证据查询
CREATE INDEX idx_disputes_evidence ON disputes USING gin(evidence);
CREATE INDEX idx_disputes_respondent_evidence ON disputes USING gin(respondent_evidence);

CREATE TRIGGER trigger_disputes_updated_at
    BEFORE UPDATE ON disputes
    FOR EACH ROW
    EXECUTE FUNCTION update_updated_at_column();