-- rCart schema — catalog entries, orders, payment splits
-- Inside rSpace shared DB, schema: rcart

CREATE TABLE IF NOT EXISTS rcart.catalog_entries (
  id              UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  artifact_id     UUID NOT NULL UNIQUE,
  artifact        JSONB NOT NULL,
  title           TEXT NOT NULL,
  product_type    TEXT,
  required_capabilities TEXT[] DEFAULT '{}',
  substrates      TEXT[] DEFAULT '{}',
  creator_id      TEXT,
  source_space    TEXT,
  tags            TEXT[] DEFAULT '{}',
  status          TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'paused', 'sold_out', 'removed')),
  created_at      TIMESTAMPTZ DEFAULT NOW(),
  updated_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_catalog_status ON rcart.catalog_entries (status) WHERE status = 'active';
CREATE INDEX IF NOT EXISTS idx_catalog_capabilities ON rcart.catalog_entries USING gin (required_capabilities);
CREATE INDEX IF NOT EXISTS idx_catalog_tags ON rcart.catalog_entries USING gin (tags);
CREATE INDEX IF NOT EXISTS idx_catalog_source_space ON rcart.catalog_entries (source_space);
CREATE INDEX IF NOT EXISTS idx_catalog_product_type ON rcart.catalog_entries (product_type);

CREATE TABLE IF NOT EXISTS rcart.orders (
  id              UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  catalog_entry_id UUID NOT NULL REFERENCES rcart.catalog_entries(id),
  artifact_id     UUID NOT NULL,
  buyer_id        TEXT,
  buyer_location  JSONB,
  buyer_contact   JSONB,
  provider_id     UUID,
  provider_name   TEXT,
  provider_distance_km DOUBLE PRECISION,
  quantity        INTEGER NOT NULL DEFAULT 1,
  production_cost NUMERIC(10,2),
  creator_payout  NUMERIC(10,2),
  community_payout NUMERIC(10,2),
  total_price     NUMERIC(10,2),
  currency        TEXT DEFAULT 'USD',
  status          TEXT NOT NULL DEFAULT 'pending' CHECK (status IN (
    'pending', 'paid', 'accepted', 'in_production', 'ready', 'shipped', 'completed', 'cancelled'
  )),
  payment_method  TEXT DEFAULT 'manual',
  payment_tx      TEXT,
  payment_network TEXT,
  created_at      TIMESTAMPTZ DEFAULT NOW(),
  paid_at         TIMESTAMPTZ,
  accepted_at     TIMESTAMPTZ,
  completed_at    TIMESTAMPTZ,
  updated_at      TIMESTAMPTZ DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_orders_status ON rcart.orders (status);
CREATE INDEX IF NOT EXISTS idx_orders_provider ON rcart.orders (provider_id);
CREATE INDEX IF NOT EXISTS idx_orders_buyer ON rcart.orders (buyer_id);
CREATE INDEX IF NOT EXISTS idx_orders_catalog ON rcart.orders (catalog_entry_id);
