-- Deploy scripts run this before applying pending files from supabase/migrations/.
-- Tracks applied SQL so incremental migrations run on existing DBs (not only first empty schema).

CREATE TABLE IF NOT EXISTS public.schema_migrations (
  filename text PRIMARY KEY,
  applied_at timestamptz NOT NULL DEFAULT now()
);

-- One-time backfill: databases that already had app schema before schema_migrations existed.
INSERT INTO public.schema_migrations (filename)
SELECT v.fn
FROM (VALUES
  ('000_supabase_schemas.sql'),
  ('001_app_schema.sql'),
  ('002_enrichment_schema.sql'),
  ('003_rls_and_campaign_failed.sql'),
  ('004_rls_enrichment_tables.sql')
) AS v(fn)
WHERE EXISTS (
  SELECT 1 FROM information_schema.tables
  WHERE table_schema = 'public' AND table_name = 'contacts'
)
AND (SELECT COUNT(*)::int FROM public.schema_migrations) = 0;
