-- Migration 091: Add store discovery tracking columns
-- Per auto-healing scheme (2025-12-12):
-- Track when store_discovery last updated each dispensary
-- Track when last payload was saved

-- Add last_store_discovery_at to track when store_discovery updated this record
ALTER TABLE dispensaries
ADD COLUMN IF NOT EXISTS last_store_discovery_at TIMESTAMPTZ;

-- Add last_payload_at to track when last product payload was saved
-- (Complements last_fetch_at which tracks API fetch time)
ALTER TABLE dispensaries
ADD COLUMN IF NOT EXISTS last_payload_at TIMESTAMPTZ;

-- Add index for finding stale discovery data
CREATE INDEX IF NOT EXISTS idx_dispensaries_store_discovery_at
ON dispensaries (last_store_discovery_at DESC NULLS LAST)
WHERE crawl_enabled = true;

-- Add index for finding dispensaries without recent payloads
CREATE INDEX IF NOT EXISTS idx_dispensaries_payload_at
ON dispensaries (last_payload_at DESC NULLS LAST)
WHERE crawl_enabled = true;

COMMENT ON COLUMN dispensaries.last_store_discovery_at IS 'When store_discovery task last updated this record';
COMMENT ON COLUMN dispensaries.last_payload_at IS 'When last product payload was saved for this dispensary';
