-- Scrape results cache
CREATE TABLE IF NOT EXISTS scrape_results (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  url TEXT NOT NULL,
  clinic_name TEXT,
  data JSONB NOT NULL DEFAULT '{}',
  created_at TIMESTAMPTZ DEFAULT NOW()
);

-- Marketing intelligence reports
CREATE TABLE IF NOT EXISTS marketing_reports (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  url TEXT NOT NULL,
  clinic_name TEXT,
  report JSONB NOT NULL DEFAULT '{}',
  scrape_data JSONB DEFAULT '{}',
  analysis_data JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ DEFAULT NOW(),
  updated_at TIMESTAMPTZ DEFAULT NOW()
);

-- Enable RLS
ALTER TABLE scrape_results ENABLE ROW LEVEL SECURITY;
ALTER TABLE marketing_reports ENABLE ROW LEVEL SECURITY;

-- Service role can do everything (Edge Functions use service_role key)
CREATE POLICY "service_role_all_scrape" ON scrape_results
  FOR ALL USING (auth.role() = 'service_role');

CREATE POLICY "service_role_all_reports" ON marketing_reports
  FOR ALL USING (auth.role() = 'service_role');

-- Anon users can read their own reports (future: add user_id column)
CREATE POLICY "anon_read_reports" ON marketing_reports
  FOR SELECT USING (true);

-- Index for faster lookups
CREATE INDEX idx_scrape_results_url ON scrape_results(url);
CREATE INDEX idx_marketing_reports_url ON marketing_reports(url);
CREATE INDEX idx_marketing_reports_created ON marketing_reports(created_at DESC);
