-- ============================================================
-- Migration: RMP Master System — Relevant Media Properties LLC
-- Timestamp: 20260401120000
-- Covers: Sales, CRM, AdOps, Accounting, Email Distribution
-- ADDITIVE ONLY — no existing tables modified
-- ============================================================

-- ─── SALES STAFF ─────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_sales_staff (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  full_name text NOT NULL,
  email text,
  phone text,
  status text DEFAULT 'active',
  terminated_date date,
  notes text,
  created_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_sales_staff_status ON public.rmp_sales_staff(status);

-- ─── COMMISSION TIERS ─────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_commission_tiers (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  staff_id uuid REFERENCES public.rmp_sales_staff(id) ON DELETE CASCADE,
  effective_year integer,
  tier_order integer,
  threshold_cents integer,
  rate numeric,
  created_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_commission_tiers_staff ON public.rmp_commission_tiers(staff_id);
CREATE INDEX IF NOT EXISTS idx_rmp_commission_tiers_year ON public.rmp_commission_tiers(effective_year);

-- ─── CLIENTS ──────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_clients (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  company_name text NOT NULL,
  contact_name text,
  contact_email text,
  contact_phone text,
  billing_address text,
  notes text,
  status text DEFAULT 'active',
  created_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_clients_status ON public.rmp_clients(status);
CREATE INDEX IF NOT EXISTS idx_rmp_clients_company ON public.rmp_clients(company_name);

-- ─── PRODUCT / SERVICE CATALOG ────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_products (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  site text NOT NULL,
  product_type text NOT NULL,
  name text NOT NULL,
  description text,
  dimensions text,
  standard_price_cents integer,
  duration_days integer,
  active boolean DEFAULT true,
  sort_order integer DEFAULT 0,
  created_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_products_site ON public.rmp_products(site);
CREATE INDEX IF NOT EXISTS idx_rmp_products_active ON public.rmp_products(active);

-- ─── ORDERS ───────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_orders (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  client_id uuid REFERENCES public.rmp_clients(id),
  staff_id uuid REFERENCES public.rmp_sales_staff(id),
  po_number text,
  internal_order_number text,
  site text NOT NULL,
  product_id uuid REFERENCES public.rmp_products(id),
  ad_unit text,
  description text,
  start_date date,
  end_date date,
  total_amount_cents integer,
  currency text DEFAULT 'USD',
  status text DEFAULT 'active',
  invoicing_schedule text DEFAULT 'single',
  next_invoice_date date,
  notes text,
  created_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_orders_client ON public.rmp_orders(client_id);
CREATE INDEX IF NOT EXISTS idx_rmp_orders_staff ON public.rmp_orders(staff_id);
CREATE INDEX IF NOT EXISTS idx_rmp_orders_site ON public.rmp_orders(site);
CREATE INDEX IF NOT EXISTS idx_rmp_orders_status ON public.rmp_orders(status);
CREATE INDEX IF NOT EXISTS idx_rmp_orders_next_invoice ON public.rmp_orders(next_invoice_date);

-- ─── INVOICES ─────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_invoices (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  order_id uuid REFERENCES public.rmp_orders(id),
  client_id uuid REFERENCES public.rmp_clients(id),
  staff_id uuid REFERENCES public.rmp_sales_staff(id),
  invoice_number text,
  site text,
  amount_cents integer,
  currency text DEFAULT 'USD',
  status text DEFAULT 'pending',
  payment_method text,
  stripe_payment_id text,
  wire_reference text,
  notes text,
  issue_date date,
  due_date date,
  paid_date date,
  is_staff_sale boolean DEFAULT false,
  created_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_invoices_order ON public.rmp_invoices(order_id);
CREATE INDEX IF NOT EXISTS idx_rmp_invoices_client ON public.rmp_invoices(client_id);
CREATE INDEX IF NOT EXISTS idx_rmp_invoices_status ON public.rmp_invoices(status);
CREATE INDEX IF NOT EXISTS idx_rmp_invoices_due_date ON public.rmp_invoices(due_date);
CREATE INDEX IF NOT EXISTS idx_rmp_invoices_site ON public.rmp_invoices(site);

-- ─── EXPENSES ─────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_expenses (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  vendor text,
  amount_cents integer,
  currency text DEFAULT 'USD',
  category text,
  description text,
  receipt_url text,
  receipt_source text,
  ai_parsed boolean DEFAULT false,
  reconciled boolean DEFAULT false,
  bank_transaction_id text,
  expense_date date,
  created_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_expenses_date ON public.rmp_expenses(expense_date);
CREATE INDEX IF NOT EXISTS idx_rmp_expenses_category ON public.rmp_expenses(category);
CREATE INDEX IF NOT EXISTS idx_rmp_expenses_reconciled ON public.rmp_expenses(reconciled);

-- ─── BANK TRANSACTIONS ────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_bank_transactions (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  transaction_date date,
  description text,
  amount_cents integer,
  type text,
  matched_invoice_id uuid,
  matched_expense_id uuid,
  reconciled boolean DEFAULT false,
  raw_csv_row jsonb,
  imported_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_bank_tx_date ON public.rmp_bank_transactions(transaction_date);
CREATE INDEX IF NOT EXISTS idx_rmp_bank_tx_reconciled ON public.rmp_bank_transactions(reconciled);

-- ─── COMMISSIONS ──────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_commissions (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  invoice_id uuid REFERENCES public.rmp_invoices(id),
  staff_id uuid REFERENCES public.rmp_sales_staff(id),
  year integer,
  sale_amount_cents integer,
  commission_rate numeric,
  commission_amount_cents integer,
  ytd_sales_at_time_cents integer,
  paid boolean DEFAULT false,
  paid_date date,
  created_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_commissions_staff ON public.rmp_commissions(staff_id);
CREATE INDEX IF NOT EXISTS idx_rmp_commissions_year ON public.rmp_commissions(year);
CREATE INDEX IF NOT EXISTS idx_rmp_commissions_paid ON public.rmp_commissions(paid);

-- ─── DOCUMENT VAULT ───────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_documents (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  document_type text,
  title text,
  year integer,
  person text,
  file_url text,
  notes text,
  uploaded_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_documents_type ON public.rmp_documents(document_type);
CREATE INDEX IF NOT EXISTS idx_rmp_documents_year ON public.rmp_documents(year);

-- ─── IO EXTENSIONS ────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_io_extensions (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  existing_io_id text NOT NULL,
  order_id uuid REFERENCES public.rmp_orders(id),
  product_id uuid REFERENCES public.rmp_products(id),
  staff_id uuid REFERENCES public.rmp_sales_staff(id),
  client_id uuid REFERENCES public.rmp_clients(id),
  is_comp boolean DEFAULT false,
  comp_reason text,
  is_paid boolean DEFAULT false,
  flight_status text DEFAULT 'scheduled',
  start_date date NOT NULL,
  end_date date,
  auto_deactivate boolean DEFAULT true,
  renewal_notice_sent boolean DEFAULT false,
  renewal_notice_sent_at timestamptz,
  reactivated_at timestamptz,
  reactivation_reason text,
  banner_image_url text,
  click_through_url text,
  alt_text text,
  email_html_url text,
  email_scheduled_date date,
  email_sent_at timestamptz,
  email_list_segment text,
  page_url text,
  newsletter_issue_date date,
  notes text,
  created_at timestamptz DEFAULT now(),
  updated_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_io_ext_flight_status ON public.rmp_io_extensions(flight_status);
CREATE INDEX IF NOT EXISTS idx_rmp_io_ext_end_date ON public.rmp_io_extensions(end_date);
CREATE INDEX IF NOT EXISTS idx_rmp_io_ext_client ON public.rmp_io_extensions(client_id);
CREATE INDEX IF NOT EXISTS idx_rmp_io_ext_staff ON public.rmp_io_extensions(staff_id);

-- ─── EMAIL SENDING DOMAINS ────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_email_sending_domains (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  site text NOT NULL,
  domain text NOT NULL,
  domain_type text DEFAULT 'subdomain',
  is_primary boolean DEFAULT false,
  is_active boolean DEFAULT false,
  sort_order integer DEFAULT 0,
  daily_send_limit integer DEFAULT 5000,
  sends_today integer DEFAULT 0,
  sends_reset_at date,
  spf_valid boolean DEFAULT false,
  spf_checked_at timestamptz,
  dkim_valid boolean DEFAULT false,
  dkim_checked_at timestamptz,
  dmarc_valid boolean DEFAULT false,
  dmarc_checked_at timestamptz,
  ptr_valid boolean DEFAULT false,
  ptr_checked_at timestamptz,
  mx_valid boolean DEFAULT false,
  mx_checked_at timestamptz,
  dns_fully_verified boolean DEFAULT false,
  blacklisted boolean DEFAULT false,
  blacklist_details text,
  blacklist_checked_at timestamptz,
  health_score integer DEFAULT 0,
  bypass_verification boolean DEFAULT false,
  bypass_reason text,
  bypass_set_by text,
  bypass_set_at timestamptz,
  last_used_at timestamptz,
  notes text,
  created_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_email_domains_site ON public.rmp_email_sending_domains(site);
CREATE INDEX IF NOT EXISTS idx_rmp_email_domains_active ON public.rmp_email_sending_domains(is_active);

-- ─── EMAIL SUPPRESSIONS ───────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_email_suppressions (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  site text NOT NULL,
  email text NOT NULL,
  suppression_type text NOT NULL,
  source text,
  reply_text text,
  sending_domain text,
  suppressed_at timestamptz DEFAULT now(),
  suppressed_by text,
  notes text,
  UNIQUE(site, email)
);

CREATE INDEX IF NOT EXISTS idx_rmp_suppressions_site ON public.rmp_email_suppressions(site);
CREATE INDEX IF NOT EXISTS idx_rmp_suppressions_email ON public.rmp_email_suppressions(email);
CREATE INDEX IF NOT EXISTS idx_rmp_suppressions_type ON public.rmp_email_suppressions(suppression_type);

-- ─── SUPPRESSION KEYWORDS ─────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_suppression_keywords (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  keyword text NOT NULL,
  keyword_type text DEFAULT 'unsubscribe',
  active boolean DEFAULT true,
  created_at timestamptz DEFAULT now()
);

-- ─── EMAIL DNS CHECK LOG ──────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_email_dns_log (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  domain_id uuid REFERENCES public.rmp_email_sending_domains(id),
  check_type text,
  passed boolean,
  result_detail text,
  checked_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_dns_log_domain ON public.rmp_email_dns_log(domain_id);

-- ─── EMAIL SEND LOG ───────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_email_send_log (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  site text NOT NULL,
  sending_domain_id uuid REFERENCES public.rmp_email_sending_domains(id),
  io_extension_id uuid REFERENCES public.rmp_io_extensions(id),
  recipient_email text,
  subject text,
  send_type text,
  status text DEFAULT 'queued',
  suppression_reason text,
  sent_at timestamptz,
  opens integer DEFAULT 0,
  clicks integer DEFAULT 0,
  bounced boolean DEFAULT false,
  bounce_type text,
  spam_complaint boolean DEFAULT false,
  created_at timestamptz DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rmp_send_log_site ON public.rmp_email_send_log(site);
CREATE INDEX IF NOT EXISTS idx_rmp_send_log_status ON public.rmp_email_send_log(status);
CREATE INDEX IF NOT EXISTS idx_rmp_send_log_domain ON public.rmp_email_send_log(sending_domain_id);

-- ─── ADOPS NOTIFICATIONS ──────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_adops_notifications (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  io_extension_id uuid REFERENCES public.rmp_io_extensions(id),
  notification_type text,
  recipient_type text,
  recipient_email text,
  recipient_phone text,
  message text,
  sent_via text,
  sent_at timestamptz DEFAULT now(),
  success boolean DEFAULT true,
  error_message text
);

CREATE INDEX IF NOT EXISTS idx_rmp_adops_notif_io ON public.rmp_adops_notifications(io_extension_id);

-- ─── PAYMENT NOTIFICATIONS ────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS public.rmp_notifications (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  type text,
  message text,
  sent_at timestamptz DEFAULT now(),
  invoice_id uuid
);

-- ─── RLS: ADMIN-ONLY ACCESS FOR ALL RMP TABLES ────────────────────────────────

CREATE OR REPLACE FUNCTION public.rmp_is_admin()
RETURNS boolean
LANGUAGE sql
STABLE
SECURITY DEFINER
AS $$
  SELECT EXISTS (
    SELECT 1 FROM public.user_profiles up
    WHERE up.id = auth.uid() AND up.role IN ('administrator', 'admin')
  )
$$;

CREATE OR REPLACE FUNCTION public.rmp_is_adops_uploader()
RETURNS boolean
LANGUAGE sql
STABLE
SECURITY DEFINER
AS $$
  SELECT EXISTS (
    SELECT 1 FROM public.user_profiles up
    WHERE up.id = auth.uid() AND up.role IN ('administrator', 'admin', 'adops_uploader')
  )
$$;

ALTER TABLE public.rmp_sales_staff ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_commission_tiers ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_clients ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_products ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_orders ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_expenses ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_bank_transactions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_commissions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_documents ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_io_extensions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_email_sending_domains ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_email_suppressions ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_suppression_keywords ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_email_dns_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_email_send_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_adops_notifications ENABLE ROW LEVEL SECURITY;
ALTER TABLE public.rmp_notifications ENABLE ROW LEVEL SECURITY;

-- Admin full access policies
DROP POLICY IF EXISTS "rmp_admin_sales_staff" ON public.rmp_sales_staff;
CREATE POLICY "rmp_admin_sales_staff" ON public.rmp_sales_staff FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_commission_tiers" ON public.rmp_commission_tiers;
CREATE POLICY "rmp_admin_commission_tiers" ON public.rmp_commission_tiers FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_clients" ON public.rmp_clients;
CREATE POLICY "rmp_admin_clients" ON public.rmp_clients FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_products" ON public.rmp_products;
CREATE POLICY "rmp_admin_products" ON public.rmp_products FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_orders" ON public.rmp_orders;
CREATE POLICY "rmp_admin_orders" ON public.rmp_orders FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_invoices" ON public.rmp_invoices;
CREATE POLICY "rmp_admin_invoices" ON public.rmp_invoices FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_expenses" ON public.rmp_expenses;
CREATE POLICY "rmp_admin_expenses" ON public.rmp_expenses FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_bank_tx" ON public.rmp_bank_transactions;
CREATE POLICY "rmp_admin_bank_tx" ON public.rmp_bank_transactions FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_commissions" ON public.rmp_commissions;
CREATE POLICY "rmp_admin_commissions" ON public.rmp_commissions FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_documents" ON public.rmp_documents;
CREATE POLICY "rmp_admin_documents" ON public.rmp_documents FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_adops_io_extensions" ON public.rmp_io_extensions;
CREATE POLICY "rmp_adops_io_extensions" ON public.rmp_io_extensions FOR ALL TO authenticated
  USING (public.rmp_is_adops_uploader()) WITH CHECK (public.rmp_is_adops_uploader());

DROP POLICY IF EXISTS "rmp_admin_email_domains" ON public.rmp_email_sending_domains;
CREATE POLICY "rmp_admin_email_domains" ON public.rmp_email_sending_domains FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_suppressions" ON public.rmp_email_suppressions;
CREATE POLICY "rmp_admin_suppressions" ON public.rmp_email_suppressions FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_keywords" ON public.rmp_suppression_keywords;
CREATE POLICY "rmp_admin_keywords" ON public.rmp_suppression_keywords FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_dns_log" ON public.rmp_email_dns_log;
CREATE POLICY "rmp_admin_dns_log" ON public.rmp_email_dns_log FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_send_log" ON public.rmp_email_send_log;
CREATE POLICY "rmp_admin_send_log" ON public.rmp_email_send_log FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_adops_notif" ON public.rmp_adops_notifications;
CREATE POLICY "rmp_admin_adops_notif" ON public.rmp_adops_notifications FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

DROP POLICY IF EXISTS "rmp_admin_notifications" ON public.rmp_notifications;
CREATE POLICY "rmp_admin_notifications" ON public.rmp_notifications FOR ALL TO authenticated
  USING (public.rmp_is_admin()) WITH CHECK (public.rmp_is_admin());

-- ─── SEED DATA ────────────────────────────────────────────────────────────────

-- Jeff Victor sales staff + commission tiers
DO $$
DECLARE
  jeff_id uuid;
BEGIN
  INSERT INTO public.rmp_sales_staff (full_name, email, status)
  VALUES ('Jeff Victor', 'jeff.victor@relevantmediaproperties.com', 'active')
  ON CONFLICT DO NOTHING
  RETURNING id INTO jeff_id;

  IF jeff_id IS NOT NULL THEN
    INSERT INTO public.rmp_commission_tiers (staff_id, effective_year, tier_order, threshold_cents, rate)
    VALUES
      (jeff_id, 2026, 1, 10000000, 0.25),
      (jeff_id, 2026, 2, NULL, 0.30)
    ON CONFLICT DO NOTHING;
  END IF;
EXCEPTION WHEN OTHERS THEN
  RAISE NOTICE 'Seed staff error: %', SQLERRM;
END $$;

-- Suppression keywords
INSERT INTO public.rmp_suppression_keywords (keyword, keyword_type) VALUES
  ('unsubscribe','unsubscribe'),('remove','unsubscribe'),('remove me','unsubscribe'),
  ('opt out','unsubscribe'),('opt-out','unsubscribe'),('stop','unsubscribe'),
  ('cancel','unsubscribe'),('do not email','unsubscribe'),('dont email','unsubscribe'),
  ('don''t email','unsubscribe'),('never email','unsubscribe'),
  ('take me off','unsubscribe'),('take me off your list','unsubscribe'),
  ('leave me alone','unsubscribe')
ON CONFLICT DO NOTHING;

-- Email sending domains
INSERT INTO public.rmp_email_sending_domains (site, domain, domain_type, is_primary, sort_order) VALUES
  ('broadcastbeat',        'news.broadcastbeat.com',         'subdomain',    true,  1),
  ('broadcastbeat',        'mail.broadcastbeat.com',         'subdomain',    false, 2),
  ('broadcastbeat',        'broadcastbeatnews.com',          'sister_domain',false, 3),
  ('avbeat',               'news.avbeat.com',                'subdomain',    true,  1),
  ('avbeat',               'mail.avbeat.com',                'subdomain',    false, 2),
  ('backlotbeat',          'news.backlotbeat.com',           'subdomain',    true,  1),
  ('backlotbeat',          'mail.backlotbeat.com',           'subdomain',    false, 2),
  ('broadcastengineering', 'news.broadcastengineering.com',  'subdomain',    true,  1),
  ('broadcastengineering', 'mail.broadcastengineering.com',  'subdomain',    false, 2)
ON CONFLICT DO NOTHING;

-- Product catalog seed for all 4 RMP sites
DO $$
DECLARE
  sites text[] := ARRAY['broadcastbeat','avbeat','backlotbeat','broadcastengineering'];
  s text;
  all_types text[] := ARRAY[
    'display_banner_300x250','display_banner_728x90','display_banner_300x600',
    'display_banner_970x250','newsletter_banner_600x100','dedicated_email_blast',
    'newsletter_sponsorship','featured_advertorial','featured_newsletter_story'
  ];
  limited_types text[] := ARRAY[
    'display_banner_300x250','display_banner_728x90','display_banner_300x600',
    'display_banner_970x250','newsletter_banner_600x100','dedicated_email_blast',
    'featured_advertorial'
  ];
  pt text;
  dims text;
  use_types text[];
BEGIN
  FOREACH s IN ARRAY sites LOOP
    IF s IN ('backlotbeat','broadcastengineering') THEN
      use_types := limited_types;
    ELSE
      use_types := all_types;
    END IF;
    FOREACH pt IN ARRAY use_types LOOP
      dims := CASE pt
        WHEN 'display_banner_300x250' THEN '300x250'
        WHEN 'display_banner_728x90'  THEN '728x90'
        WHEN 'display_banner_300x600' THEN '300x600'
        WHEN 'display_banner_970x250' THEN '970x250'
        WHEN 'newsletter_banner_600x100' THEN '600x100'
        ELSE NULL
      END;
      INSERT INTO public.rmp_products (site, product_type, name, dimensions, active)
      VALUES (s, pt, initcap(replace(pt,'_',' ')), dims, true)
      ON CONFLICT DO NOTHING;
    END LOOP;
  END LOOP;
EXCEPTION WHEN OTHERS THEN
  RAISE NOTICE 'Product seed error: %', SQLERRM;
END $$;
