Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

50.3 KB
Raw Blame
-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.

-- Ships these rules to databases where `authz sync` does not run after migrations yet.

CREATE OR REPLACE FUNCTION public.assert_audit_log_access(p_company_id text, p_permission text)
 RETURNS void
 LANGUAGE plpgsql
 STABLE SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
BEGIN
  IF current_setting('role', true) NOT IN ('anon', 'authenticated') THEN
    RETURN;
  END IF;

  IF p_permission IS NOT NULL AND p_company_id = ANY (
    COALESCE(get_companies_with_employee_permission(p_permission), '{}')::text[]
  ) THEN
    RETURN;
  END IF;

  RAISE EXCEPTION 'Not authorized to access the audit log for this company'
    USING ERRCODE = 'insufficient_privilege';
END;
$function$;

CREATE OR REPLACE FUNCTION public.attach_audit_log_append_only(p_table_name text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  EXECUTE format('DROP TRIGGER IF EXISTS "append_only" ON %I', p_table_name);
  EXECUTE format(
    'CREATE TRIGGER "append_only" BEFORE UPDATE OR DELETE ON %I
       FOR EACH ROW EXECUTE FUNCTION prevent_audit_log_mutation()',
    p_table_name
  );
END;
$function$;

CREATE OR REPLACE FUNCTION public.attach_event_trigger(table_name_text text, sync_functions text[] DEFAULT ARRAY[]::text[], after_sync_functions text[] DEFAULT ARRAY[]::text[])
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  sync_args TEXT;
  after_sync_args TEXT;
BEGIN
  -- A. Attach BEFORE SYNC Trigger (Row Level) -- unchanged behavior
  IF array_length(sync_functions, 1) > 0 THEN
      SELECT string_agg(quote_literal(x), ', ') INTO sync_args FROM unnest(sync_functions) x;

      EXECUTE format('
        DROP TRIGGER IF EXISTS "trg_event_sync_%1$s" ON %1$I;
        CREATE TRIGGER "trg_event_sync_%1$s"
        BEFORE INSERT OR UPDATE OR DELETE ON %1$I
        FOR EACH ROW
        EXECUTE FUNCTION public.dispatch_event_interceptors(%2$s);
      ', table_name_text, sync_args);
  ELSE
      EXECUTE format('DROP TRIGGER IF EXISTS "trg_event_sync_%1$s" ON %1$I;', table_name_text);
  END IF;

  -- B. Attach AFTER SYNC Trigger (Row Level) -- NEW
  IF array_length(after_sync_functions, 1) > 0 THEN
      SELECT string_agg(quote_literal(x), ', ') INTO after_sync_args FROM unnest(after_sync_functions) x;

      EXECUTE format('
        DROP TRIGGER IF EXISTS "trg_event_after_sync_%1$s" ON %1$I;
        CREATE TRIGGER "trg_event_after_sync_%1$s"
        AFTER INSERT OR UPDATE OR DELETE ON %1$I
        FOR EACH ROW
        EXECUTE FUNCTION public.dispatch_event_after_interceptors(%2$s);
      ', table_name_text, after_sync_args);
  ELSE
      EXECUTE format('DROP TRIGGER IF EXISTS "trg_event_after_sync_%1$s" ON %1$I;', table_name_text);
  END IF;

  -- C. Attach ASYNC Triggers (Statement Level) -- unchanged behavior
  -- 1. INSERT
  EXECUTE format('
    DROP TRIGGER IF EXISTS "trg_event_async_ins_%1$s" ON %1$I;
    CREATE TRIGGER "trg_event_async_ins_%1$s"
    AFTER INSERT ON %1$I
    REFERENCING NEW TABLE AS batched_new
    FOR EACH STATEMENT
    EXECUTE FUNCTION public.dispatch_event_batch();
  ', table_name_text);

  -- 2. DELETE
  EXECUTE format('
    DROP TRIGGER IF EXISTS "trg_event_async_del_%1$s" ON %1$I;
    CREATE TRIGGER "trg_event_async_del_%1$s"
    AFTER DELETE ON %1$I
    REFERENCING OLD TABLE AS batched_old
    FOR EACH STATEMENT
    EXECUTE FUNCTION public.dispatch_event_batch();
  ', table_name_text);

  -- 3. UPDATE
  EXECUTE format('
    DROP TRIGGER IF EXISTS "trg_event_async_upd_%1$s" ON %1$I;
    CREATE TRIGGER "trg_event_async_upd_%1$s"
    AFTER UPDATE ON %1$I
    REFERENCING NEW TABLE AS batched_new OLD TABLE AS batched_old
    FOR EACH STATEMENT
    EXECUTE FUNCTION public.dispatch_event_batch();
  ', table_name_text);

END;
$function$;

CREATE OR REPLACE FUNCTION public.attach_statement_handler(table_name_text text, handler_functions text[] DEFAULT ARRAY[]::text[])
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  fn TEXT;
  existing TEXT;
BEGIN
  -- Drop-then-attach, like attach_event_trigger's sync sections: re-running is
  -- idempotent and an empty array detaches.
  FOR existing IN
    SELECT t.tgname
    FROM pg_trigger t
    WHERE t.tgrelid = format('%I', table_name_text)::regclass
      AND NOT t.tgisinternal
      AND t.tgname LIKE 'trg\_event\_statement\_%'
  LOOP
    EXECUTE format('DROP TRIGGER IF EXISTS %2$I ON %1$I;', table_name_text, existing);
  END LOOP;

  -- One function serves all three operations, so it must branch on TG_OP: only
  -- batched_new exists on INSERT and only batched_old on DELETE. PL/pgSQL plans
  -- lazily, so a branch that does not run never resolves its missing table.
  FOREACH fn IN ARRAY handler_functions LOOP
    EXECUTE format('
      CREATE TRIGGER %2$I AFTER INSERT ON %1$I
      REFERENCING NEW TABLE AS batched_new
      FOR EACH STATEMENT EXECUTE FUNCTION %3$I();
    ', table_name_text, format('trg_event_statement_%s_ins', fn), fn);

    EXECUTE format('
      CREATE TRIGGER %2$I AFTER UPDATE ON %1$I
      REFERENCING NEW TABLE AS batched_new OLD TABLE AS batched_old
      FOR EACH STATEMENT EXECUTE FUNCTION %3$I();
    ', table_name_text, format('trg_event_statement_%s_upd', fn), fn);

    EXECUTE format('
      CREATE TRIGGER %2$I AFTER DELETE ON %1$I
      REFERENCING OLD TABLE AS batched_old
      FOR EACH STATEMENT EXECUTE FUNCTION %3$I();
    ', table_name_text, format('trg_event_statement_%s_del', fn), fn);
  END LOOP;
END;
$function$;

CREATE OR REPLACE FUNCTION public.create_audit_log_table(p_company_id text)
 RETURNS void
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
DECLARE
  tbl_name TEXT;
  tbl REGCLASS;
BEGIN
  PERFORM assert_audit_log_access(p_company_id, 'settings_update');

  tbl_name := 'auditLog_' || p_company_id;

  IF EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
  ) THEN
    -- Table exists; ensure recordId column is present (for tables created before this migration)
    IF NOT EXISTS (
      SELECT 1 FROM information_schema.columns
      WHERE table_schema = 'public'
        AND information_schema.columns.table_name = tbl_name
        AND column_name = 'recordId'
    ) THEN
      EXECUTE format('ALTER TABLE %I ADD COLUMN "recordId" TEXT', tbl_name);
      EXECUTE format('UPDATE %I SET "recordId" = "entityId" WHERE "recordId" IS NULL', tbl_name);
      EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("recordId")',
        'idx_' || tbl_name || '_record', tbl_name);
    END IF;

    tbl := format('public.%I', tbl_name)::regclass;

    -- Without row level security the company-scoped read policy below is not
    -- enforced, and the API roles keep SELECT.
    IF NOT (SELECT c.relrowsecurity FROM pg_class c WHERE c.oid = tbl) THEN
      EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', tbl_name);
    END IF;

    IF NOT EXISTS (
      SELECT 1 FROM pg_trigger t
      WHERE t.tgrelid = tbl
        AND t.tgname = 'append_only'
        AND NOT t.tgisinternal
        AND t.tgenabled <> 'D'
        AND t.tgfoid = 'public.prevent_audit_log_mutation'::regproc
    ) THEN
      PERFORM attach_audit_log_append_only(tbl_name);
    END IF;

    -- Secured means: the company-scoped read policy is there, the old
    -- open policy is not, and the API roles cannot write.
    IF EXISTS (
         SELECT 1 FROM pg_policies p
         WHERE p.schemaname = 'public' AND p.tablename = tbl_name
           AND p.policyname = 'audit_log_access'
       )
       OR NOT EXISTS (
         SELECT 1 FROM pg_policies p
         WHERE p.schemaname = 'public' AND p.tablename = tbl_name
           AND p.policyname = 'SELECT' AND p.cmd = 'SELECT'
           AND p.qual LIKE '%' || quote_literal(p_company_id) || '%'
           AND p.qual LIKE '%settings_view%'
       )
       OR has_table_privilege('anon', tbl, 'INSERT, UPDATE, DELETE, TRUNCATE')
       OR has_table_privilege('authenticated', tbl, 'INSERT, UPDATE, DELETE, TRUNCATE')
    THEN
      PERFORM secure_audit_log_table(p_company_id);
    END IF;

    RETURN;
  END IF;

  EXECUTE format('
    CREATE TABLE IF NOT EXISTS %I (
      "id" TEXT PRIMARY KEY DEFAULT id(''aud''),
      "tableName" TEXT NOT NULL,
      "entityType" TEXT NOT NULL,
      "entityId" TEXT NOT NULL,
      "recordId" TEXT,
      "operation" TEXT NOT NULL CHECK ("operation" IN (''INSERT'', ''UPDATE'', ''DELETE'')),
      "actorId" TEXT,
      "diff" JSONB,
      "metadata" JSONB,
      "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()
    )
  ', tbl_name);

  EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("entityType", "entityId")',
    'idx_' || tbl_name || '_entity', tbl_name);
  EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("tableName")',
    'idx_' || tbl_name || '_table', tbl_name);
  EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("recordId")',
    'idx_' || tbl_name || '_record', tbl_name);
  EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("actorId")',
    'idx_' || tbl_name || '_actor', tbl_name);
  EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("createdAt" DESC)',
    'idx_' || tbl_name || '_created', tbl_name);

  EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', tbl_name);

  PERFORM attach_audit_log_append_only(tbl_name);
  PERFORM secure_audit_log_table(p_company_id);
END;
$function$;

CREATE OR REPLACE FUNCTION public.create_company_search_index(p_company_id text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_table_name TEXT;
BEGIN
  v_table_name := 'searchIndex_' || p_company_id;

  -- Create the search index table
  EXECUTE format('
    CREATE TABLE IF NOT EXISTS %I (
      "id" BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
      "entityType" TEXT NOT NULL,
      "entityId" TEXT NOT NULL,
      "title" TEXT NOT NULL,
      "description" TEXT DEFAULT '''',
      "link" TEXT NOT NULL,
      "tags" TEXT[] DEFAULT ''{}'',
      "metadata" JSONB DEFAULT ''{}'',
      "searchVector" TSVECTOR,
      "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
      "updatedAt" TIMESTAMP WITH TIME ZONE,
      CONSTRAINT %I UNIQUE ("entityType", "entityId")
    )', v_table_name, v_table_name || '_entity_unique');

  -- GIN on searchVector: FTS path (multi-word, stemmed prefix via :*).
  EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("searchVector")',
    v_table_name || '_fts_idx', v_table_name);

  -- GIN trigram on title: substring path (find "269" inside "S000269").
  EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("title" gin_trgm_ops)',
    v_table_name || '_title_trgm_idx', v_table_name);

  -- GIN trigram on description: substring path for hits that live in the body text.
  EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I USING GIN ("description" gin_trgm_ops)',
    v_table_name || '_description_trgm_idx', v_table_name);

  -- Enable RLS (no SELECT policies - access via service role bypass)
  EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', v_table_name);

  INSERT INTO "searchIndexRegistry" ("companyId")
  VALUES (p_company_id)
  ON CONFLICT ("companyId") DO NOTHING;
END;
$function$;

CREATE OR REPLACE FUNCTION public.create_embedding_subscriptions_for_company(p_company_id text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_tables TEXT[] := ARRAY['item', 'customer', 'supplier'];
  v_table TEXT;
BEGIN
  FOREACH v_table IN ARRAY v_tables LOOP
    INSERT INTO "eventSystemSubscription" (
      "name",
      "table",
      "companyId",
      "operations",
      "handlerType",
      "config",
      "filter",
      "active"
    )
    VALUES (
      'embedding-' || v_table,
      v_table,
      p_company_id,
      ARRAY['INSERT', 'UPDATE'],
      'EMBEDDING',
      '{}'::jsonb,
      '{}'::jsonb,
      TRUE
    )
    ON CONFLICT ON CONSTRAINT "unique_subscription_name_per_company"
    DO UPDATE SET
      "operations" = EXCLUDED."operations",
      "handlerType" = EXCLUDED."handlerType",
      "active" = EXCLUDED."active";
  END LOOP;
END;
$function$;

CREATE OR REPLACE FUNCTION public.create_event_system_subscription(p_name text, p_table text, p_company_id text, p_operations text[], p_handler_type text, p_config jsonb DEFAULT '{}'::jsonb, p_filter jsonb DEFAULT '{}'::jsonb, p_active boolean DEFAULT true)
 RETURNS TABLE(id text, name text, "handlerType" text, "table" text)
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public', 'pg_temp'
AS $function$
BEGIN
  IF NOT util.can_manage_event_subscription(p_company_id, p_handler_type) THEN
    RAISE EXCEPTION 'Not authorized to manage % event subscriptions for company %', p_handler_type, p_company_id
      USING ERRCODE = '42501';
  END IF;

  RETURN QUERY
  INSERT INTO "eventSystemSubscription" (
    "name", "table", "companyId", "operations",
    "handlerType", "config", "filter", "active"
  )
  VALUES (
    p_name, p_table, p_company_id, p_operations,
    p_handler_type, p_config, p_filter, p_active
  )
  ON CONFLICT ON CONSTRAINT "unique_subscription_name_per_company"
  DO UPDATE SET
    "operations" = EXCLUDED."operations",
    "filter" = EXCLUDED."filter",
    "handlerType" = EXCLUDED."handlerType",
    "config" = EXCLUDED."config",
    "active" = EXCLUDED."active"
  -- Replacing a subscription also needs the right to manage what it was.
  WHERE util.can_manage_event_subscription(
    p_company_id,
    "eventSystemSubscription"."handlerType"
  )
  RETURNING
    "eventSystemSubscription"."id",
    "eventSystemSubscription"."name",
    "eventSystemSubscription"."handlerType",
    "eventSystemSubscription"."table";

  IF NOT FOUND THEN
    RAISE EXCEPTION 'Not authorized to replace event subscription "%" for company %', p_name, p_company_id
      USING ERRCODE = '42501';
  END IF;
END;
$function$;

CREATE OR REPLACE FUNCTION public.create_search_subscriptions_for_company(p_company_id text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_tables TEXT[] := ARRAY[
    'employee', 'customer', 'supplier', 'item', 'job', 
    'purchaseOrder', 'salesInvoice', 'purchaseInvoice', 
    'nonConformance', 'gauge', 'quote', 'salesRfq', 
    'salesOrder', 'supplierQuote'
  ];
  v_table TEXT;
BEGIN
  FOREACH v_table IN ARRAY v_tables LOOP
    INSERT INTO "eventSystemSubscription" (
      "name", 
      "table", 
      "companyId", 
      "operations", 
      "handlerType", 
      "config", 
      "filter", 
      "active"
    )
    VALUES (
      'search-index-' || v_table,
      v_table,
      p_company_id,
      ARRAY['INSERT', 'UPDATE', 'DELETE'],
      'SEARCH',
      '{}'::jsonb,
      '{}'::jsonb,
      TRUE
    )
    ON CONFLICT ON CONSTRAINT "unique_subscription_name_per_company" 
    DO UPDATE SET
      "operations" = EXCLUDED."operations",
      "handlerType" = EXCLUDED."handlerType",
      "active" = EXCLUDED."active";
  END LOOP;
END;
$function$;

CREATE OR REPLACE FUNCTION public.delete_event_system_subscription(p_subscription_id text)
 RETURNS void
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public', 'pg_temp'
AS $function$
DECLARE
  v_company_id TEXT;
  v_handler_type TEXT;
BEGIN
  SELECT "companyId", "handlerType" INTO v_company_id, v_handler_type
  FROM "eventSystemSubscription"
  WHERE "id" = p_subscription_id;

  -- Nothing to delete (missing id, or already gone) — no-op, as before.
  IF v_company_id IS NULL THEN
    RETURN;
  END IF;

  IF NOT util.can_manage_event_subscription(v_company_id, v_handler_type) THEN
    RAISE EXCEPTION 'Not authorized to manage % event subscriptions for company %', v_handler_type, v_company_id
      USING ERRCODE = '42501';
  END IF;

  DELETE FROM "eventSystemSubscription" WHERE "id" = p_subscription_id;
END;
$function$;

CREATE OR REPLACE FUNCTION public.delete_event_system_subscriptions_by_name(p_company_id text, p_name text)
 RETURNS void
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public', 'pg_temp'
AS $function$
DECLARE
  v_handler_type TEXT;
BEGIN
  -- A (companyId, name) group is one handler type in practice; if any matching
  -- row is WEBHOOK, require the stricter WEBHOOK gate. NULL (no rows) falls
  -- through to the membership gate on a delete that affects nothing.
  SELECT CASE WHEN bool_or("handlerType" = 'WEBHOOK') THEN 'WEBHOOK' ELSE max("handlerType") END
  INTO v_handler_type
  FROM "eventSystemSubscription"
  WHERE "companyId" = p_company_id AND "name" = p_name;

  IF NOT util.can_manage_event_subscription(p_company_id, COALESCE(v_handler_type, '')) THEN
    RAISE EXCEPTION 'Not authorized to manage event subscriptions for company %', p_company_id
      USING ERRCODE = '42501';
  END IF;

  DELETE FROM "eventSystemSubscription"
  WHERE "companyId" = p_company_id AND "name" = p_name;
END;
$function$;

CREATE OR REPLACE FUNCTION public.delete_from_search_index(p_company_id text, p_entity_type text, p_entity_id text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_table_name TEXT;
BEGIN
  v_table_name := 'searchIndex_' || p_company_id;
  
  EXECUTE format(
    'DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2',
    v_table_name
  ) USING p_entity_type, p_entity_id;
END;
$function$;

CREATE OR REPLACE FUNCTION public.delete_old_audit_logs(p_company_id text, p_cutoff_date timestamp with time zone)
 RETURNS integer
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
DECLARE
  tbl_name TEXT;
  deleted_count INTEGER;
BEGIN
  PERFORM assert_audit_log_access(p_company_id, NULL);

  tbl_name := 'auditLog_' || p_company_id;

  IF NOT EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
  ) THEN
    RETURN 0;
  END IF;

  -- Authorize the append-only trigger to permit these retention deletes.
  PERFORM set_config('app.audit_archiving', 'on', true);

  EXECUTE format('
    WITH deleted AS (
      DELETE FROM %I
      WHERE "createdAt" < $1
      RETURNING *
    )
    SELECT COUNT(*) FROM deleted
  ', tbl_name)
  USING p_cutoff_date
  INTO deleted_count;

  RETURN deleted_count;
END;
$function$;

CREATE OR REPLACE FUNCTION public.dispatch_event_after_interceptors()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
DECLARE
  func_name TEXT;
  payload_data JSONB;
  old_payload_data JSONB;
  i INTEGER;
BEGIN
  -- A. Normalize Data
  IF TG_OP = 'DELETE' THEN
    payload_data := row_to_json(OLD)::jsonb;
    old_payload_data := payload_data;
  ELSIF TG_OP = 'INSERT' THEN
    payload_data := row_to_json(NEW)::jsonb;
    old_payload_data := NULL;
  ELSE -- UPDATE
    payload_data := row_to_json(NEW)::jsonb;
    old_payload_data := row_to_json(OLD)::jsonb;
  END IF;

  -- B. Execute AFTER Interceptor Functions
  -- Same calling convention as dispatch_event_interceptors():
  --   function_name(table_name TEXT, operation TEXT, new_data JSONB, old_data JSONB)
  FOR i IN 0 .. (TG_NARGS - 1) LOOP
    func_name := TG_ARGV[i];
    EXECUTE format('SELECT public.%I($1, $2, $3, $4)', func_name)
    USING TG_TABLE_NAME::TEXT, TG_OP, payload_data, old_payload_data;
  END LOOP;

  IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
END;
$function$;

CREATE OR REPLACE FUNCTION public.dispatch_event_batch()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public', 'pgmq', 'extensions'
AS $function$
DECLARE
  sub RECORD;
  msg_batch JSONB[];
  rec_company_id TEXT;
  has_subs BOOLEAN;
  current_actor_id TEXT;
  current_workflow_run_id TEXT;
  pk_column TEXT;
  pk_join TEXT;
  query_text TEXT;
  did_enqueue BOOLEAN := FALSE;
  ignored_columns CONSTANT TEXT[] := ARRAY['updatedAt', 'updatedBy', 'embedding'];
BEGIN
  current_actor_id := auth.uid()::TEXT;
  current_workflow_run_id :=
    (nullif(current_setting('request.jwt.claims', true), '')::jsonb)->>'workflow_run_id';
  pk_column := public.get_primary_key_column(TG_TABLE_NAME);

  -- Pair UPDATE rows on the full key: single-column pairing cross-joins rows
  -- on tables with composite identity.
  SELECT string_agg(format('n.%I = o.%I', col, col), ' AND ')
    INTO pk_join
  FROM unnest(public.get_primary_key_columns(TG_TABLE_NAME)) AS col;

  IF TG_OP = 'DELETE' THEN
    SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;
  ELSIF TG_OP = 'INSERT' THEN
    SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
  ELSE
    SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
  END IF;

  IF rec_company_id IS NULL THEN RETURN NULL; END IF;

  SELECT EXISTS (
    SELECT 1 FROM "eventSystemSubscription"
    WHERE "table" = TG_TABLE_NAME
      AND "companyId" = rec_company_id
      AND "active" = TRUE
      AND TG_OP = ANY("operations")
      AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
           OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
  ) INTO has_subs;

  IF NOT has_subs THEN RETURN NULL; END IF;

  FOR sub IN
    SELECT * FROM "eventSystemSubscription"
    WHERE "table" = TG_TABLE_NAME
      AND "companyId" = rec_company_id
      AND "active" = TRUE
      AND TG_OP = ANY("operations")
      AND ("handlerType" NOT IN ('SYNC','WEBHOOK','WORKFLOW')
           OR current_setting('app.sync_in_progress', true) IS DISTINCT FROM 'true')
  LOOP

    IF TG_OP = 'INSERT' THEN
        query_text := format('
            SELECT array_agg(
                jsonb_build_object(
                    ''subscriptionId'', $1,
                    ''triggerType'', $2,
                    ''handlerType'', $3,
                    ''handlerConfig'', $4,
                    ''companyId'', $5,
                    ''actorId'', $6,
                    ''workflowRunId'', $10,
                    ''event'', jsonb_build_object(
                        ''table'', $7,
                        ''operation'', $8,
                        ''recordId'', t.%I::TEXT,
                        ''new'', row_to_json(t)::jsonb,
                        ''old'', null,
                        ''timestamp'', clock_timestamp()
                    )
                )
            )
            FROM batched_new t
            WHERE t."companyId" = $5
              AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
        ', pk_column);

        EXECUTE query_text INTO msg_batch
        USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
              current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
              current_workflow_run_id;

    ELSIF TG_OP = 'DELETE' THEN
        query_text := format('
            SELECT array_agg(
                jsonb_build_object(
                    ''subscriptionId'', $1,
                    ''triggerType'', $2,
                    ''handlerType'', $3,
                    ''handlerConfig'', $4,
                    ''companyId'', $5,
                    ''actorId'', $6,
                    ''workflowRunId'', $10,
                    ''event'', jsonb_build_object(
                        ''table'', $7,
                        ''operation'', $8,
                        ''recordId'', t.%I::TEXT,
                        ''new'', null,
                        ''old'', row_to_json(t)::jsonb,
                        ''timestamp'', clock_timestamp()
                    )
                )
            )
            FROM batched_old t
            WHERE t."companyId" = $5
              AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
        ', pk_column);

        EXECUTE query_text INTO msg_batch
        USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
              current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
              current_workflow_run_id;

    ELSIF TG_OP = 'UPDATE' THEN
        query_text := format('
            SELECT array_agg(
                jsonb_build_object(
                    ''subscriptionId'', $1,
                    ''triggerType'', $2,
                    ''handlerType'', $3,
                    ''handlerConfig'', $4,
                    ''companyId'', $5,
                    ''actorId'', $6,
                    ''workflowRunId'', $10,
                    ''event'', jsonb_build_object(
                        ''table'', $7,
                        ''operation'', $8,
                        ''recordId'', n.%I::TEXT,
                        ''new'', row_to_json(n)::jsonb,
                        ''old'', row_to_json(o)::jsonb,
                        ''timestamp'', clock_timestamp()
                    )
                )
            )
            FROM batched_new n
            JOIN batched_old o ON %s
            WHERE n."companyId" = $5
              AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)
              AND (NOT $11 OR (to_jsonb(n) - $12) IS DISTINCT FROM (to_jsonb(o) - $12))
        ', pk_column, pk_join);

        EXECUTE query_text INTO msg_batch
        USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
              current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter,
              current_workflow_run_id,
              sub."handlerType" IN ('AUDIT', 'SEARCH', 'EMBEDDING'),
              ignored_columns;
    END IF;

    IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN
      PERFORM pgmq.send_batch('event_system', msg_batch);
      did_enqueue := TRUE;
    END IF;

  END LOOP;

  -- Wake the Inngest drainer once per transaction: the GUC is txn-local, so a
  -- bulk import posts a single doorbell instead of one per statement.
  IF did_enqueue
     AND current_setting('carbon.event_wake_sent', true) IS DISTINCT FROM 'true' THEN
    PERFORM util.wake_event_queue();
    PERFORM set_config('carbon.event_wake_sent', 'true', true);
  END IF;

  RETURN NULL;
END;
$function$;

CREATE OR REPLACE FUNCTION public.dispatch_event_interceptors()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public'
AS $function$
DECLARE
  func_name TEXT;
  payload_data JSONB;
  old_payload_data JSONB;
  i INTEGER;
BEGIN
  -- A. Normalize Data
  IF TG_OP = 'DELETE' THEN
    payload_data := row_to_json(OLD)::jsonb;
    old_payload_data := payload_data;
  ELSIF TG_OP = 'INSERT' THEN
    payload_data := row_to_json(NEW)::jsonb;
    old_payload_data := NULL;
  ELSE -- UPDATE
    payload_data := row_to_json(NEW)::jsonb;
    old_payload_data := row_to_json(OLD)::jsonb;
  END IF;

  -- B. Execute Interceptor Functions
  -- Loop through arguments passed in CREATE TRIGGER ... EXECUTE FUNCTION func(arg1, arg2)
  FOR i IN 0 .. (TG_NARGS - 1) LOOP
    func_name := TG_ARGV[i];
    EXECUTE format('SELECT public.%I($1, $2, $3, $4)', func_name)
    USING TG_TABLE_NAME::TEXT, TG_OP, payload_data, old_payload_data;
  END LOOP;

  IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
END;
$function$;

CREATE OR REPLACE FUNCTION public.drop_audit_log_table(p_company_id text)
 RETURNS void
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
DECLARE
  tbl_name TEXT;
BEGIN
  PERFORM assert_audit_log_access(p_company_id, NULL);

  tbl_name := 'auditLog_' || p_company_id;

  EXECUTE format('DROP TABLE IF EXISTS %I CASCADE', tbl_name);
END;
$function$;

CREATE OR REPLACE FUNCTION public.drop_company_search_index(p_company_id text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_table_name TEXT;
BEGIN
  v_table_name := 'searchIndex_' || p_company_id;

  -- Drop the search index table if it exists
  EXECUTE format('DROP TABLE IF EXISTS %I', v_table_name);

  -- Remove from registry
  DELETE FROM "searchIndexRegistry" WHERE "companyId" = p_company_id;
END;
$function$;

CREATE OR REPLACE FUNCTION public.get_audit_log(p_company_id text, p_entity_type text DEFAULT NULL::text, p_entity_id text DEFAULT NULL::text, p_actor_id text DEFAULT NULL::text, p_operation text DEFAULT NULL::text, p_start_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_end_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_search text DEFAULT NULL::text)
 RETURNS TABLE(id text, "tableName" text, "entityType" text, "entityId" text, operation text, "actorId" text, diff jsonb, metadata jsonb, "createdAt" timestamp with time zone, "totalCount" bigint)
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
DECLARE
  tbl_name TEXT;
  where_clauses TEXT[] := ARRAY[]::TEXT[];
  where_clause TEXT := '';
  query_text TEXT;
  count_query TEXT;
  total BIGINT;
BEGIN
  PERFORM assert_audit_log_access(p_company_id, 'settings_view');

  tbl_name := 'auditLog_' || p_company_id;

  IF NOT EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
  ) THEN
    RETURN;
  END IF;

  IF p_entity_type IS NOT NULL THEN
    where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
  END IF;

  IF p_entity_id IS NOT NULL THEN
    where_clauses := array_append(where_clauses, format('"entityId" = %L', p_entity_id));
  END IF;

  IF p_actor_id IS NOT NULL THEN
    where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
  END IF;

  IF p_operation IS NOT NULL THEN
    where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
  END IF;

  IF p_start_date IS NOT NULL THEN
    where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
  END IF;

  IF p_end_date IS NOT NULL THEN
    where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
  END IF;

  IF p_search IS NOT NULL AND p_search != '' THEN
    where_clauses := array_append(where_clauses,
      format('"entityId" ILIKE %L', '%' || p_search || '%'));
  END IF;

  IF array_length(where_clauses, 1) > 0 THEN
    where_clause := 'WHERE ' || array_to_string(where_clauses, ' AND ');
  END IF;

  count_query := format('SELECT COUNT(*) FROM %I %s', tbl_name, where_clause);
  EXECUTE count_query INTO total;

  query_text := format('
    SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt", %s::BIGINT as "totalCount"
    FROM %I
    %s
    ORDER BY "createdAt" DESC
    LIMIT %s OFFSET %s
  ', total, tbl_name, where_clause, p_limit, p_offset);

  RETURN QUERY EXECUTE query_text;
END;
$function$;

CREATE OR REPLACE FUNCTION public.get_audit_log_count(p_company_id text, p_entity_type text DEFAULT NULL::text, p_actor_id text DEFAULT NULL::text, p_operation text DEFAULT NULL::text, p_start_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_end_date timestamp with time zone DEFAULT NULL::timestamp with time zone, p_search text DEFAULT NULL::text)
 RETURNS integer
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
DECLARE
  tbl_name TEXT;
  where_clauses TEXT[] := ARRAY[]::TEXT[];
  where_clause TEXT := '';
  count_val INTEGER;
BEGIN
  PERFORM assert_audit_log_access(p_company_id, 'settings_view');

  tbl_name := 'auditLog_' || p_company_id;

  IF NOT EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
  ) THEN
    RETURN 0;
  END IF;

  IF p_entity_type IS NOT NULL THEN
    where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
  END IF;

  IF p_actor_id IS NOT NULL THEN
    where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
  END IF;

  IF p_operation IS NOT NULL THEN
    where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
  END IF;

  IF p_start_date IS NOT NULL THEN
    where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
  END IF;

  IF p_end_date IS NOT NULL THEN
    where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
  END IF;

  IF p_search IS NOT NULL AND p_search != '' THEN
    where_clauses := array_append(where_clauses,
      format('"entityId" ILIKE %L', '%' || p_search || '%'));
  END IF;

  IF array_length(where_clauses, 1) > 0 THEN
    where_clause := 'WHERE ' || array_to_string(where_clauses, ' AND ');
  END IF;

  EXECUTE format('SELECT COUNT(*)::INTEGER FROM %I %s', tbl_name, where_clause) INTO count_val;
  RETURN count_val;
END;
$function$;

CREATE OR REPLACE FUNCTION public.get_audit_logs_for_archive(p_company_id text, p_before_date timestamp with time zone)
 RETURNS TABLE(id text, "tableName" text, "entityType" text, "entityId" text, operation text, "actorId" text, diff jsonb, metadata jsonb, "createdAt" timestamp with time zone)
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
DECLARE
  tbl_name TEXT;
BEGIN
  PERFORM assert_audit_log_access(p_company_id, NULL);

  tbl_name := 'auditLog_' || p_company_id;

  IF NOT EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
  ) THEN
    RETURN;
  END IF;

  RETURN QUERY EXECUTE format('
    SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt"
    FROM %I
    WHERE "createdAt" < $1
    ORDER BY "createdAt" ASC
  ', tbl_name)
  USING p_before_date;
END;
$function$;

CREATE OR REPLACE FUNCTION public.get_entity_audit_log(p_company_id text, p_entity_type text, p_entity_id text, p_limit integer DEFAULT 50, p_offset integer DEFAULT 0, p_record_id text DEFAULT NULL::text)
 RETURNS TABLE(id text, "tableName" text, "entityType" text, "entityId" text, "recordId" text, operation text, "actorId" text, diff jsonb, metadata jsonb, "createdAt" timestamp with time zone)
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
DECLARE
  tbl_name TEXT;
BEGIN
  PERFORM assert_audit_log_access(p_company_id, 'settings_view');

  tbl_name := 'auditLog_' || p_company_id;

  IF NOT EXISTS (
    SELECT 1 FROM information_schema.tables
    WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
  ) THEN
    RETURN;
  END IF;

  IF p_record_id IS NULL THEN
    RETURN QUERY EXECUTE format('
      SELECT "id", "tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt"
      FROM %I
      WHERE "entityType" = $1 AND "entityId" = $2
      ORDER BY "createdAt" DESC
      LIMIT $3 OFFSET $4
    ', tbl_name)
    USING p_entity_type, p_entity_id, p_limit, p_offset;
  ELSE
    RETURN QUERY EXECUTE format('
      SELECT "id", "tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt"
      FROM %I
      WHERE "entityType" = $1 AND "entityId" = $2 AND "recordId" = $3
      ORDER BY "createdAt" DESC
      LIMIT $4 OFFSET $5
    ', tbl_name)
    USING p_entity_type, p_entity_id, p_record_id, p_limit, p_offset;
  END IF;
END;
$function$;

CREATE OR REPLACE FUNCTION public.get_primary_key_column(p_table_name text)
 RETURNS text
 LANGUAGE plpgsql
 STABLE
AS $function$
DECLARE
  pk_column TEXT;
BEGIN
  -- First try to get primary key
  SELECT a.attname INTO pk_column
  FROM pg_index i
  JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
  WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
    AND i.indisprimary
  LIMIT 1;
  
  -- If no primary key, try to get any unique index column
  IF pk_column IS NULL THEN
    SELECT a.attname INTO pk_column
    FROM pg_index i
    JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
    WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
    LIMIT 1;
  END IF;
  
  RETURN COALESCE(pk_column, 'id');
END;
$function$;

CREATE OR REPLACE FUNCTION public.get_primary_key_columns(p_table_name text)
 RETURNS text[]
 LANGUAGE plpgsql
 STABLE
AS $function$
DECLARE
  pk_columns TEXT[];
BEGIN
  -- All columns of the primary key
  SELECT array_agg(a.attname ORDER BY a.attnum) INTO pk_columns
  FROM pg_index i
  JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
  WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
    AND i.indisprimary;

  -- No PK: key columns of the smallest valid, non-partial, non-expression
  -- unique index. Partial/expression indexes don't guarantee row identity for
  -- every row, and INCLUDE columns (positions past indnkeyatts) aren't part of
  -- the uniqueness constraint — the slice keeps key columns only.
  IF pk_columns IS NULL THEN
    SELECT array_agg(a.attname ORDER BY a.attnum) INTO pk_columns
    FROM pg_index i
    JOIN pg_attribute a ON a.attrelid = i.indrelid
      AND a.attnum = ANY ((i.indkey::int2[])[1:i.indnkeyatts])
    WHERE i.indexrelid = (
      SELECT i2.indexrelid
      FROM pg_index i2
      WHERE i2.indrelid = ('"' || p_table_name || '"')::regclass
        AND i2.indisunique
        AND i2.indisvalid
        AND i2.indpred IS NULL
        AND i2.indexprs IS NULL
      ORDER BY i2.indnkeyatts ASC
      LIMIT 1
    );
  END IF;

  -- Last resort: the legacy single-column resolver
  IF pk_columns IS NULL OR array_length(pk_columns, 1) IS NULL THEN
    pk_columns := ARRAY[public.get_primary_key_column(p_table_name)];
  END IF;

  RETURN pk_columns;
END;
$function$;

CREATE OR REPLACE FUNCTION public.insert_audit_log_batch(p_company_id text, p_entries jsonb[])
 RETURNS integer
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
DECLARE
  tbl_name TEXT;
  inserted_count INTEGER := 0;
BEGIN
  PERFORM assert_audit_log_access(p_company_id, NULL);

  tbl_name := 'auditLog_' || p_company_id;

  PERFORM create_audit_log_table(p_company_id);

  -- createdAt is the entry's own (the original event time) when it has one.
  -- clock_timestamp() is evaluated per row, so the rest still get distinct
  -- values rather than sharing NOW().
  EXECUTE format('
    INSERT INTO %I ("tableName", "entityType", "entityId", "recordId", "operation", "actorId", "diff", "metadata", "createdAt")
    SELECT
      e->>''tableName'',
      e->>''entityType'',
      e->>''entityId'',
      e->>''recordId'',
      e->>''operation'',
      e->>''actorId'',
      NULLIF(e->''diff'', ''null''::jsonb),
      NULLIF(e->''metadata'', ''null''::jsonb),
      COALESCE((e->>''createdAt'')::TIMESTAMPTZ, clock_timestamp())
    FROM unnest($1) AS e
  ', tbl_name)
  USING p_entries;
  GET DIAGNOSTICS inserted_count = ROW_COUNT;

  RETURN inserted_count;
END;
$function$;

CREATE OR REPLACE FUNCTION public.on_company_created_search_index()
 RETURNS trigger
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
BEGIN
  PERFORM create_company_search_index(NEW.id);
  PERFORM create_search_subscriptions_for_company(NEW.id);
  PERFORM create_embedding_subscriptions_for_company(NEW.id);
  RETURN NEW;
END;
$function$;

CREATE OR REPLACE FUNCTION public.populate_company_search_index(p_company_id text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_table_name TEXT := 'searchIndex_' || p_company_id;
BEGIN
  -- Populate employees
  EXECUTE format('
    INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
    SELECT
      ''employee'',
      e.id,
      COALESCE(u."fullName", ''''),
      ''/x/person/'' || e.id,
      ARRAY_REMOVE(ARRAY[et.name], NULL),
      jsonb_build_object(''active'', e.active),
      to_tsvector(''english'', COALESCE(u."fullName", '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[et.name], NULL), '' ''), ''''))
    FROM "employee" e
    INNER JOIN "user" u ON u.id = e.id
    LEFT JOIN "employeeType" et ON et.id = e."employeeTypeId"
    WHERE e."companyId" = $1 AND e.active = true
    ON CONFLICT ("entityType", "entityId") DO UPDATE SET
      "title" = EXCLUDED."title",
      "tags" = EXCLUDED."tags",
      "metadata" = EXCLUDED."metadata",
      "searchVector" = EXCLUDED."searchVector",
      "updatedAt" = NOW()
  ', v_table_name) USING p_company_id;

  -- Populate customers (join customerTax for taxId)
  EXECUTE format('
    INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
    SELECT
      ''customer'',
      c.id,
      c.name,
      ''/x/customer/'' || c.id,
      ARRAY_REMOVE(ARRAY[ct.name, cs.name], NULL),
      jsonb_build_object(''taxId'', ctx."taxId"),
      to_tsvector(''english'', c.name || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[ct.name, cs.name], NULL), '' ''), ''''))
    FROM "customer" c
    LEFT JOIN "customerTax" ctx ON ctx."customerId" = c.id
    LEFT JOIN "customerType" ct ON ct.id = c."customerTypeId"
    LEFT JOIN "customerStatus" cs ON cs.id = c."customerStatusId"
    WHERE c."companyId" = $1
    ON CONFLICT ("entityType", "entityId") DO UPDATE SET
      "title" = EXCLUDED."title",
      "tags" = EXCLUDED."tags",
      "metadata" = EXCLUDED."metadata",
      "searchVector" = EXCLUDED."searchVector",
      "updatedAt" = NOW()
  ', v_table_name) USING p_company_id;

  -- Populate suppliers (join supplierTax for taxId)
  EXECUTE format('
    INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
    SELECT
      ''supplier'',
      s.id,
      s.name,
      ''/x/supplier/'' || s.id,
      ARRAY_REMOVE(ARRAY[st.name, s."supplierStatus"::TEXT], NULL),
      jsonb_build_object(''taxId'', stx."taxId"),
      to_tsvector(''english'', s.name || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[st.name, s."supplierStatus"::TEXT], NULL), '' ''), ''''))
    FROM "supplier" s
    LEFT JOIN "supplierTax" stx ON stx."supplierId" = s.id
    LEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"
    WHERE s."companyId" = $1
    ON CONFLICT ("entityType", "entityId") DO UPDATE SET
      "title" = EXCLUDED."title",
      "tags" = EXCLUDED."tags",
      "metadata" = EXCLUDED."metadata",
      "searchVector" = EXCLUDED."searchVector",
      "updatedAt" = NOW()
  ', v_table_name) USING p_company_id;
END;
$function$;

CREATE OR REPLACE FUNCTION public.prevent_audit_log_mutation()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
BEGIN
  IF TG_OP = 'UPDATE' THEN
    RAISE EXCEPTION 'Audit log records are immutable (append-only)';
  END IF;
  -- DELETE: permitted only during retention/archival, which sets this flag.
  IF current_setting('app.audit_archiving', true) IS DISTINCT FROM 'on' THEN
    RAISE EXCEPTION 'Audit log records cannot be deleted (retention/archival only)';
  END IF;
  RETURN OLD;
END;
$function$;

CREATE OR REPLACE FUNCTION public.search_company_index(p_company_id text, p_query text, p_entity_types text[], p_limit integer DEFAULT 20)
 RETURNS TABLE(id bigint, "entityType" text, "entityId" text, title text, description text, link text, tags text[], metadata jsonb)
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_table_name TEXT;
  v_sanitized TEXT;
  v_tsquery_text TEXT;
  v_like_pattern TEXT;
  v_prefix_pattern TEXT;
BEGIN
  v_table_name := 'searchIndex_' || p_company_id;

  -- Strip tsquery operators; keep alphanumerics, whitespace, `_`, `-`.
  v_sanitized := regexp_replace(coalesce(trim(p_query), ''), '[^[:alnum:][:space:]_-]', ' ', 'g');
  v_sanitized := trim(regexp_replace(v_sanitized, '\s+', ' ', 'g'));

  IF v_sanitized = '' THEN
    RETURN;
  END IF;

  -- Build `tok1:* & tok2:* & ...` for the FTS branch (word-prefix match).
  SELECT string_agg(tok || ':*', ' & ')
    INTO v_tsquery_text
    FROM regexp_split_to_table(v_sanitized, '\s+') AS tok
   WHERE tok ~ '[[:alnum:]]';

  -- Defensive fallback - should not trigger in practice since v_sanitized is
  -- non-empty and contains at least one alnum, but keep the function robust.
  IF v_tsquery_text IS NULL OR v_tsquery_text = '' THEN
    RETURN;
  END IF;

  -- Substring + prefix patterns use the ORIGINAL sanitized string so users
  -- can search by any slice of a stored title (e.g. "269" inside "S000269").
  v_like_pattern   := '%' || v_sanitized || '%';
  v_prefix_pattern := v_sanitized || '%';

  RETURN QUERY EXECUTE format('
    WITH q AS (
      SELECT to_tsquery(''english'', $1) AS query
    )
    SELECT
      si.id,
      si."entityType",
      si."entityId",
      si.title,
      si.description,
      si.link,
      si.tags,
      si.metadata
    FROM %I si, q
    WHERE si."entityType" = ANY($2)
      AND (
        si."searchVector" @@ q.query
        OR si.title ILIKE $4
        OR si.description ILIKE $4
      )
    ORDER BY
      -- Boost rows where the title starts with the query (e.g. typing "S000"
      -- pins "S000269" to the top).
      CASE WHEN si.title ILIKE $5 THEN 0 ELSE 1 END,
      ts_rank_cd(si."searchVector", q.query) DESC,
      si.id DESC
    LIMIT $3
  ', v_table_name)
  USING v_tsquery_text, p_entity_types, p_limit, v_like_pattern, v_prefix_pattern;
END;
$function$;

CREATE OR REPLACE FUNCTION public.secure_audit_log_table(p_company_id text)
 RETURNS void
 LANGUAGE plpgsql
 SET search_path TO 'public'
AS $function$
DECLARE
  tbl_name TEXT := 'auditLog_' || p_company_id;
BEGIN
  EXECUTE format('DROP POLICY IF EXISTS "audit_log_access" ON %I', tbl_name);
  EXECUTE format('DROP POLICY IF EXISTS "SELECT" ON %I', tbl_name);
  EXECUTE format(
    'CREATE POLICY "SELECT" ON %I FOR SELECT USING (
       %L = ANY ((SELECT get_companies_with_employee_permission(''settings_view''))::text[])
     )',
    tbl_name, p_company_id
  );
  EXECUTE format(
    'REVOKE INSERT, UPDATE, DELETE, TRUNCATE ON %I FROM anon, authenticated',
    tbl_name
  );
END;
$function$;

CREATE OR REPLACE FUNCTION public.upsert_to_search_index(p_company_id text, p_entity_type text, p_entity_id text, p_title text, p_description text, p_link text, p_tags text[], p_metadata jsonb)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  v_table_name TEXT;
  v_search_text TEXT;
BEGIN
  v_table_name := 'searchIndex_' || p_company_id;
  v_search_text := p_title || ' ' || COALESCE(p_description, '') || ' ' || COALESCE(array_to_string(p_tags, ' '), '');
  
  EXECUTE format('
    INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")
    VALUES ($1, $2, $3, $4, $5, $6, $7, to_tsvector(''english'', $8))
    ON CONFLICT ("entityType", "entityId") DO UPDATE SET
      "title" = EXCLUDED."title",
      "description" = EXCLUDED."description",
      "link" = EXCLUDED."link",
      "tags" = EXCLUDED."tags",
      "metadata" = EXCLUDED."metadata",
      "searchVector" = EXCLUDED."searchVector",
      "updatedAt" = NOW()
  ', v_table_name) USING 
    p_entity_type, 
    p_entity_id, 
    p_title, 
    COALESCE(p_description, ''),
    p_link, 
    COALESCE(p_tags, ARRAY[]::text[]), 
    COALESCE(p_metadata, '{}'::jsonb),
    v_search_text;
END;
$function$;

CREATE OR REPLACE FUNCTION util.anon_key()
 RETURNS text
 LANGUAGE plpgsql
 SECURITY DEFINER
AS $function$
DECLARE
  anon_key text;
BEGIN
  SELECT "anonKey" INTO  anon_key FROM "config" LIMIT 1;
  RETURN anon_key;
END;
$function$;

CREATE OR REPLACE FUNCTION util.can_manage_event_subscription(p_company_id text, p_handler_type text)
 RETURNS boolean
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public', 'pg_temp'
AS $function$
BEGIN
  IF (SELECT auth.role()) = 'service_role' THEN
    RETURN TRUE;
  END IF;

  IF p_handler_type = 'WEBHOOK' THEN
    RETURN p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_permission('settings_create'))::text[], ARRAY[]::text[]))
        OR p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_permission('settings_update'))::text[], ARRAY[]::text[]))
        OR p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_permission('settings_delete'))::text[], ARRAY[]::text[]));
  END IF;

  RETURN p_company_id = ANY (COALESCE((SELECT get_companies_with_employee_role())::text[], ARRAY[]::text[]));
END;
$function$;

CREATE OR REPLACE FUNCTION util.clear_column()
 RETURNS trigger
 LANGUAGE plpgsql
AS $function$
DECLARE
    clear_column text := TG_ARGV[0];
BEGIN
    NEW := NEW #= hstore(clear_column, NULL);
    RETURN NEW;
END;
$function$;

CREATE OR REPLACE FUNCTION util.invoke_edge_function(name text, body jsonb, timeout_milliseconds integer DEFAULT ((5 * 60) * 1000))
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  headers_raw text;
  auth_header text;
BEGIN
  -- If we're in a PostgREST session, reuse the request headers for authorization
  headers_raw := current_setting('request.headers', true);

  -- Only try to parse if headers are present
  auth_header := CASE
    WHEN headers_raw IS NOT NULL THEN
      (headers_raw::json->>'authorization')
    ELSE
      'Bearer ' || util.anon_key()
  END;

  -- Perform async HTTP request to the edge function
  PERFORM net.http_post(
    url => util.api_url() || '/functions/v1/' || name,
    headers => jsonb_build_object(
      'Content-Type', 'application/json',
      'Authorization', auth_header
    ),
    body => body,
    timeout_milliseconds => timeout_milliseconds
  );
END;
$function$;

CREATE OR REPLACE FUNCTION util.process_embeddings(batch_size integer DEFAULT 10, max_requests integer DEFAULT 10, timeout_milliseconds integer DEFAULT ((5 * 60) * 1000))
 RETURNS void
 LANGUAGE plpgsql
AS $function$
DECLARE
  job_batches JSONB[];
  batch JSONB;
BEGIN
  WITH
    -- First get jobs and assign batch numbers
    numbered_jobs AS (
      SELECT
        message || jsonb_build_object('jobId', msg_id) AS job_info,
        (row_number() OVER (ORDER BY 1) - 1) / batch_size AS batch_num
      FROM pgmq.read(
        queue_name => 'embedding_jobs',
        vt => timeout_milliseconds / 1000,
        qty => max_requests * batch_size
      )
    ),
    -- Then group jobs into batches
    batched_jobs AS (
      SELECT
        jsonb_agg(job_info) AS batch_array,
        batch_num
      FROM numbered_jobs
      GROUP BY batch_num
    )
  -- Finally aggregate all batches into array, defaulting to an empty array
  -- (FOREACH errors on NULL arrays, e.g. when the queue has no pending jobs)
  SELECT COALESCE(array_agg(batch_array), ARRAY[]::JSONB[])
  FROM batched_jobs
  INTO job_batches;

  -- Invoke the embed edge function for each batch
  FOREACH batch IN ARRAY job_batches LOOP
    PERFORM util.invoke_edge_function(
      name => 'embed',
      body => batch,
      timeout_milliseconds => timeout_milliseconds
    );
  END LOOP;
END;
$function$;

CREATE OR REPLACE FUNCTION util.queue_embeddings(record_id text, embedding_table text)
 RETURNS void
 LANGUAGE plpgsql
AS $function$
BEGIN
  PERFORM pgmq.send(
    queue_name => 'embedding_jobs',
    msg => jsonb_build_object(
      'id', record_id,
      'table', embedding_table
    )
  );
END;
$function$;

CREATE OR REPLACE FUNCTION util.sweep_event_queue()
 RETURNS void
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public', 'pgmq', 'extensions'
AS $function$
BEGIN
  -- Only visible messages count: rows hidden by a read's visibility timeout
  -- are already being drained and must not trigger a spurious wake.
  IF EXISTS (
    SELECT 1 FROM pgmq.q_event_system WHERE vt <= clock_timestamp()
  ) THEN
    PERFORM util.wake_event_queue();
  END IF;
END;
$function$;

CREATE OR REPLACE FUNCTION util.wake_event_queue()
 RETURNS void
 LANGUAGE plpgsql
 SECURITY DEFINER
 SET search_path TO 'public', 'extensions'
AS $function$
DECLARE
  api_url TEXT;
  anon_key TEXT;
BEGIN
  SELECT "apiUrl", "anonKey" INTO api_url, anon_key FROM "config" LIMIT 1;

  IF api_url IS NULL THEN
    RETURN;
  END IF;

  PERFORM net.http_post(
    api_url || '/functions/v1/event-wake',
    '{}'::jsonb,
    '{}'::jsonb,
    jsonb_build_object(
      'Content-Type', 'application/json',
      'Authorization', 'Bearer ' || anon_key
    )
  );
EXCEPTION WHEN OTHERS THEN
  RAISE LOG 'wake_event_queue failed: % %', SQLERRM, SQLSTATE;
END;
$function$;