-- Phase 3: price tracking. The refetch worker pulls product data for items that
-- carry a URL (generic Shopify .json adapter first), updates the item's metadata
-- columns, and appends a row to price_history on every successful fetch.

-- Per-item tracking control + last fetch outcome.
ALTER TABLE items
    ADD COLUMN track_enabled BOOLEAN NOT NULL DEFAULT true,
    ADD COLUMN last_error    TEXT,
    ADD COLUMN checked_at    TIMESTAMPTZ;   -- last fetch attempt (success or failure)

-- Append-only price observations. One row per successful fetch.
CREATE TABLE price_history (
    id         UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    item_id    UUID NOT NULL REFERENCES items(id) ON DELETE CASCADE,
    price      NUMERIC(12, 2) NOT NULL,
    currency   TEXT NOT NULL,
    in_stock   BOOLEAN,
    fetched_at TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX idx_price_history_item ON price_history(item_id, fetched_at DESC);

-- Worker scan: trackable items that have a URL, cheapest checked first.
CREATE INDEX idx_items_trackable ON items(checked_at NULLS FIRST)
    WHERE url IS NOT NULL AND track_enabled;
