-- Generative-engine optimisation: what AI search actually reads.
--
-- The existing LocalBusiness/Product markup makes a store *findable* by
-- ChatGPT, Gemini, Claude and Perplexity. It does not make it *citable*. Those
-- engines assemble answers from extractable, question-shaped prose; structured
-- data mostly disambiguates which entity the prose is about. The columns here
-- exist to close that gap, plus the commerce facts AI shopping surfaces read
-- and that we could not previously state without inventing them.
--
-- Idempotent; safe to re-run.
BEGIN;

ALTER TABLE store.store_branding
  -- Merchant-written Q&A, merged with the questions we can already answer from
  -- the address, hours and delivery radius. Shape:
  --   [{ "question": "...", "answer": "..." }]
  ADD COLUMN IF NOT EXISTS "faqs" JSONB,

  -- Per-merchant control over AI crawlers.
  --
  -- Default TRUE, and deliberately so: a shop that cannot be read cannot be
  -- recommended, and for local retail being named in an AI answer is closer to
  -- free custom than to a rights problem. Merchants who disagree need a lever,
  -- which is what this is — see the robots.txt handler in web/src/server.ts.
  ADD COLUMN IF NOT EXISTS "allowAiCrawlers" BOOLEAN NOT NULL DEFAULT TRUE,

  -- Feeds schema.org MerchantReturnPolicy. Emitted only when set: a return
  -- window is a promise, and guessing one publishes a promise the merchant
  -- never made.
  ADD COLUMN IF NOT EXISTS "returnWindowDays" INTEGER,

  -- Free-delivery threshold in paise, feeding Offer.shippingDetails. Null
  -- means "not stated", not "no free delivery" — the difference matters,
  -- because the markup is omitted entirely rather than claiming a figure.
  ADD COLUMN IF NOT EXISTS "freeDeliveryOverPaise" INTEGER;

ALTER TABLE store.store_branding
  DROP CONSTRAINT IF EXISTS store_branding_return_window;
ALTER TABLE store.store_branding
  ADD CONSTRAINT store_branding_return_window CHECK (
    "returnWindowDays" IS NULL OR ("returnWindowDays" >= 0 AND "returnWindowDays" <= 365)
  );

ALTER TABLE store.store_branding
  DROP CONSTRAINT IF EXISTS store_branding_free_delivery;
ALTER TABLE store.store_branding
  ADD CONSTRAINT store_branding_free_delivery CHECK (
    "freeDeliveryOverPaise" IS NULL OR "freeDeliveryOverPaise" >= 0
  );

COMMENT ON COLUMN store.store_branding."faqs" IS
  '[{ question, answer }] — merchant-written, merged with generated answers about address, hours and delivery.';
COMMENT ON COLUMN store.store_branding."allowAiCrawlers" IS
  'When false, robots.txt disallows GPTBot, ClaudeBot, PerplexityBot and friends for this tenant.';
COMMENT ON COLUMN store.store_branding."returnWindowDays" IS
  'Days a customer has to return an item. Feeds MerchantReturnPolicy; omitted from markup when null.';

COMMIT;
