-- Create dispensaries table as single source of truth
-- This consolidates azdhs_list (official data) + stores (menu data) into one table
CREATE TABLE IF NOT EXISTS dispensaries (
  -- Primary key
  id SERIAL PRIMARY KEY,

  -- Link to source data
  azdhs_id INTEGER UNIQUE REFERENCES azdhs_list(id),

  -- AZDHS official data (source of truth for legal/address info)
  name VARCHAR(255) NOT NULL,
  company_name VARCHAR(255),
  address VARCHAR(500) NOT NULL,
  city VARCHAR(100) NOT NULL,
  state VARCHAR(2) NOT NULL,
  zip VARCHAR(10),
  status_line VARCHAR(100),
  azdhs_url TEXT,
  latitude DECIMAL(10, 8),
  longitude DECIMAL(11, 8),

  -- Enriched data (source of truth from Google Maps)
  dba_name VARCHAR(255),                    -- "Doing Business As" - display name
  phone VARCHAR(20),                        -- From Google Maps, not AZDHS
  email VARCHAR(255),                       -- From Google Maps (rare)
  website TEXT,                             -- From Google Maps, not AZDHS
  google_rating DECIMAL(2, 1),              -- e.g., 4.7
  google_review_count INTEGER,              -- e.g., 1234

  -- Menu/scraper configuration
  menu_url TEXT,                            -- Dutchie or custom menu URL
  scraper_template VARCHAR(100),            -- 'sol-flower', 'curaleaf', 'deeply-rooted', 'generic-dutchie'
  scraper_config JSONB,                     -- Store age gate settings, special navigation patterns
  last_menu_scrape TIMESTAMP,
  menu_scrape_status VARCHAR(50) DEFAULT 'pending',  -- 'pending', 'active', 'needs_recrawl', 'failed', 'no_menu'

  -- SEO and routing
  slug VARCHAR(255) UNIQUE NOT NULL,

  -- Metadata
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Create indexes for common queries
CREATE INDEX IF NOT EXISTS idx_dispensaries_city ON dispensaries(city);
CREATE INDEX IF NOT EXISTS idx_dispensaries_state ON dispensaries(state);
CREATE INDEX IF NOT EXISTS idx_dispensaries_slug ON dispensaries(slug);
CREATE INDEX IF NOT EXISTS idx_dispensaries_azdhs_id ON dispensaries(azdhs_id);
CREATE INDEX IF NOT EXISTS idx_dispensaries_menu_status ON dispensaries(menu_scrape_status);

-- Create index for location-based queries
CREATE INDEX IF NOT EXISTS idx_dispensaries_location ON dispensaries(latitude, longitude) WHERE latitude IS NOT NULL AND longitude IS NOT NULL;
