-- Morning Summary: webhooks, config, and run history

CREATE TABLE IF NOT EXISTS morning_summary_webhooks (
  id SERIAL PRIMARY KEY,
  label TEXT NOT NULL,
  webhook_url TEXT NOT NULL,
  enabled BOOLEAN NOT NULL DEFAULT true,
  last_delivered_at TIMESTAMPTZ,
  last_status TEXT,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS morning_summary_config (
  id INTEGER PRIMARY KEY DEFAULT 1 CHECK (id = 1),
  weekend_suppression BOOLEAN NOT NULL DEFAULT true,
  monday_extended_window BOOLEAN NOT NULL DEFAULT true,
  severity_filter INTEGER NOT NULL DEFAULT 2,
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

INSERT INTO morning_summary_config (id, weekend_suppression, monday_extended_window, severity_filter)
VALUES (1, true, true, 2)
ON CONFLICT (id) DO NOTHING;

CREATE TABLE IF NOT EXISTS morning_summaries (
  id SERIAL PRIMARY KEY,
  generated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  window_from TIMESTAMPTZ NOT NULL,
  window_to TIMESTAMPTZ NOT NULL,
  open_count INTEGER NOT NULL DEFAULT 0,
  resolved_count INTEGER NOT NULL DEFAULT 0,
  mttr_minutes INTEGER,
  clients_affected TEXT[] NOT NULL DEFAULT '{}',
  is_weekend_window BOOLEAN NOT NULL DEFAULT false,
  card_payload JSONB,
  delivery_status JSONB NOT NULL DEFAULT '{}'
);

CREATE INDEX IF NOT EXISTS idx_morning_summaries_generated_at ON morning_summaries(generated_at DESC);

INSERT INTO morning_summary_webhooks (label, webhook_url, enabled) VALUES
  ('Technical / On-Call',      'https://appriver3651004158.webhook.office.com/webhookb2/43394fff-d546-440f-ae34-eed04c5bcd5d@1c260a52-b84d-4b7a-a179-44971dbc3949/IncomingWebhook/fe9e1350791f4923bdbd56c076eae6ed/ee54b2ef-4f27-4188-b865-47fda0eae4d1/V2y29hRVISyBYOdDq6dPs-ekvlhqCF6XGE3yUUFxt1dKQ1', true),
  ('Technical / Outages-Issues','https://appriver3651004158.webhook.office.com/webhookb2/43394fff-d546-440f-ae34-eed04c5bcd5d@1c260a52-b84d-4b7a-a179-44971dbc3949/IncomingWebhook/b7cf42691520467986db5a993dcd07b6/ee54b2ef-4f27-4188-b865-47fda0eae4d1/V2kdADKBhv3h3CfOfeIbe3O6HI5hIh4BRVX5UMqIxhLE81', false),
  ('Finance (Testing)',         'https://appriver3651004158.webhook.office.com/webhookb2/033405b3-b02e-4ce5-a200-4a3b9f387c92@1c260a52-b84d-4b7a-a179-44971dbc3949/IncomingWebhook/5fe8882c1c0342a7bbe91d763abbca57/ee54b2ef-4f27-4188-b865-47fda0eae4d1/V2rSVLy80XTdPJlBJVzUBYrMyrTi_Tmts46dA8BZjlPaw1', false)
ON CONFLICT DO NOTHING;
