-- Migration 044: Add provider_detection_data column to dispensaries
--
-- This column stores detection metadata for menu provider discovery.
-- Used by menu-detection.ts and discovery.ts to track:
--   - Detected provider type
--   - Resolution attempts
--   - Error messages
--   - not_crawlable flag
--
-- Run with: psql $CANNAIQ_DB_URL -f migrations/044_add_provider_detection_data.sql
--
-- ALL CHANGES ARE ADDITIVE - NO DROPS, NO DELETES, NO TRUNCATES.

-- Add provider_detection_data to dispensaries table
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1 FROM information_schema.columns
    WHERE table_name = 'dispensaries' AND column_name = 'provider_detection_data'
  ) THEN
    ALTER TABLE dispensaries
      ADD COLUMN provider_detection_data JSONB DEFAULT NULL;

    RAISE NOTICE 'Added provider_detection_data column to dispensaries table';
  ELSE
    RAISE NOTICE 'provider_detection_data column already exists on dispensaries table';
  END IF;
END;
$$ LANGUAGE plpgsql;

-- Add index for querying by not_crawlable flag
CREATE INDEX IF NOT EXISTS idx_dispensaries_provider_detection_not_crawlable
  ON dispensaries ((provider_detection_data->>'not_crawlable'))
  WHERE provider_detection_data IS NOT NULL;

-- Add index for querying by detected provider
CREATE INDEX IF NOT EXISTS idx_dispensaries_provider_detection_provider
  ON dispensaries ((provider_detection_data->>'detected_provider'))
  WHERE provider_detection_data IS NOT NULL;

COMMENT ON COLUMN dispensaries.provider_detection_data IS 'JSONB metadata from menu provider detection. Keys: detected_provider, resolution_error, not_crawlable, detection_timestamp';

-- =====================================================
-- MIGRATION COMPLETE
-- =====================================================
