-- Migration: 00034_bootstrap_admins
-- Description: Bootstrap admin access using an application-owned email list.
-- Author: Codex
-- Date: 2026-01-22
--
-- This migration promotes users to admins based on a comma-separated list of
-- emails supplied via the `app.admin_bootstrap_emails` database setting.
-- It fails loudly if no admins are promoted to prevent lockout.

DO $$
DECLARE
  raw_emails TEXT;
  normalized_emails TEXT[];
  promoted_count INTEGER;
BEGIN
  raw_emails := current_setting('app.admin_bootstrap_emails', true);

  IF raw_emails IS NULL OR btrim(raw_emails) = '' THEN
    RAISE EXCEPTION
      'Missing app.admin_bootstrap_emails setting. Set it to a comma-separated list of admin emails before running this migration.';
  END IF;

  normalized_emails := ARRAY(
    SELECT lower(trim(value))
    FROM unnest(string_to_array(raw_emails, ',')) AS value
    WHERE btrim(value) <> ''
  );

  IF array_length(normalized_emails, 1) IS NULL THEN
    RAISE EXCEPTION
      'app.admin_bootstrap_emails setting must contain at least one email address.';
  END IF;

  UPDATE public.users
  SET is_admin = TRUE
  WHERE lower(email) = ANY (normalized_emails);

  GET DIAGNOSTICS promoted_count = ROW_COUNT;

  IF promoted_count = 0 THEN
    RAISE EXCEPTION
      'No admin users were promoted. Ensure app.admin_bootstrap_emails matches existing user emails.';
  END IF;
END $$;
