-- Community contributions: public users may submit new/supplementary product
-- archives. Submissions go to a moderation queue and never touch the product
-- tables until an admin approves them.

-- Community source used to record field-level provenance for approved
-- public contributions (lower trust than manual operator edits).
INSERT INTO source (name, homepage, license, trust_weight, notes)
VALUES ('community', NULL, 'user-contributed', 0.50, '公众投稿/众包贡献，经人工审核后收纳')
ON CONFLICT (name) DO NOTHING;

CREATE TABLE IF NOT EXISTS submission (
    id                UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    gtin              VARCHAR(14),
    name              TEXT NOT NULL,
    payload           JSONB NOT NULL DEFAULT '{}',
    target_product_id UUID REFERENCES product(id) ON DELETE SET NULL,
    result_product_id UUID REFERENCES product(id) ON DELETE SET NULL,
    submitter_name    TEXT,
    submitter_contact TEXT,
    note              TEXT,
    status            VARCHAR(16) NOT NULL DEFAULT 'pending',
    review_note       TEXT,
    reviewed_by       TEXT,
    reviewed_at       TIMESTAMPTZ,
    remote_ip         TEXT,
    created_at        TIMESTAMPTZ NOT NULL DEFAULT now(),
    CONSTRAINT submission_status_chk CHECK (status IN ('pending','approved','rejected'))
);

CREATE INDEX IF NOT EXISTS idx_submission_status ON submission (status, created_at DESC);
