-- ============================================================
-- v3.5 MercadoLibre Questions & Answers
-- ============================================================
-- Adds table for tracking buyer questions on ML listings.
-- All tables live in the tenant DB.
-- ============================================================

CREATE TABLE IF NOT EXISTS marketplace_questions (
    id                      SERIAL PRIMARY KEY,
    listing_id              INTEGER REFERENCES marketplace_listings(id) ON DELETE SET NULL,
    external_question_id    VARCHAR(50) NOT NULL UNIQUE,
    external_item_id        VARCHAR(50) NOT NULL,
    question_text           TEXT NOT NULL,
    answer_text             TEXT,
    status                  VARCHAR(20) DEFAULT 'unanswered',  -- unanswered, answered, closed
    buyer_id                VARCHAR(50),
    buyer_nickname          VARCHAR(100),
    question_date           TIMESTAMPTZ,
    answer_date             TIMESTAMPTZ,
    raw_json                JSONB,
    created_at              TIMESTAMPTZ DEFAULT NOW(),
    updated_at              TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_marketplace_questions_status
    ON marketplace_questions(status);
CREATE INDEX IF NOT EXISTS idx_marketplace_questions_listing
    ON marketplace_questions(listing_id);
CREATE INDEX IF NOT EXISTS idx_marketplace_questions_external
    ON marketplace_questions(external_question_id);
