-- AI Ticket Analyzer — link-aware bundle support.
-- See docs/wulf-pulse-ticket-analyzer-build-notes.md (Phase 3).
--
-- A "bundle" is an aggregate report that was triggered from a single ticket
-- analysis page (typically a master/problem ticket) and is waiting for the
-- per-ticket analyses of its referenced tickets to complete before it can run.
--
-- Adds:
--   1. expected_ticket_numbers TEXT[]   — the full set the bundle is waiting on
--   2. triggered_by_ticket_number TEXT  — the master ticket the user clicked from
--   3. New status value 'pending_analyses' — set while underlying analyses are
--      still running. Worker chain-trigger flips it to 'pending' once all
--      expected tickets have a complete analysis, then runAggregateReport runs.

ALTER TABLE analyzer_aggregate_reports
  ADD COLUMN IF NOT EXISTS expected_ticket_numbers TEXT[],
  ADD COLUMN IF NOT EXISTS triggered_by_ticket_number TEXT;

ALTER TABLE analyzer_aggregate_reports
  DROP CONSTRAINT IF EXISTS analyzer_aggregate_reports_status_check;

ALTER TABLE analyzer_aggregate_reports
  ADD CONSTRAINT analyzer_aggregate_reports_status_check
  CHECK (status IN ('pending','pending_analyses','running','complete','failed'));

-- Replace the existing partial index so chain-trigger queries are still fast.
DROP INDEX IF EXISTS idx_analyzer_aggregate_reports_pending;
CREATE INDEX IF NOT EXISTS idx_analyzer_aggregate_reports_pending
  ON analyzer_aggregate_reports (status, generated_at)
  WHERE status IN ('pending','pending_analyses','running');

-- Worker chain-trigger looks up reports waiting on a specific ticket number.
CREATE INDEX IF NOT EXISTS idx_analyzer_aggregate_reports_expected_tickets
  ON analyzer_aggregate_reports USING gin (expected_ticket_numbers)
  WHERE status = 'pending_analyses';

COMMENT ON COLUMN analyzer_aggregate_reports.expected_ticket_numbers IS
  'For bundles created from a master ticket: the full set of ticket numbers whose '
  'analyses must complete before the aggregate-reduce step runs. NULL for legacy '
  'aggregate reports created by manual multi-select.';

COMMENT ON COLUMN analyzer_aggregate_reports.triggered_by_ticket_number IS
  'The ticket number the bundle was launched from (the master in a problem-ticket '
  'flow). NULL for legacy reports.';
