-- Ticket Digest Report tables
-- Stores config, delivery webhooks, and report history for LLM-analyzed ticket digest reports

CREATE TABLE IF NOT EXISTS ticket_digest_config (
  id INTEGER PRIMARY KEY DEFAULT 1,
  daily_enabled BOOLEAN NOT NULL DEFAULT false,
  weekly_enabled BOOLEAN NOT NULL DEFAULT false,
  monthly_enabled BOOLEAN NOT NULL DEFAULT false,
  daily_cron VARCHAR(50) NOT NULL DEFAULT '0 7 * * 1-5',
  weekly_cron VARCHAR(50) NOT NULL DEFAULT '0 7 * * 1',
  monthly_cron VARCHAR(50) NOT NULL DEFAULT '0 7 1 * *',
  llm_provider VARCHAR(20) NOT NULL DEFAULT 'anthropic',
  llm_model VARCHAR(100) NOT NULL DEFAULT 'claude-sonnet-4-20250514',
  include_noise_analysis BOOLEAN NOT NULL DEFAULT true,
  include_sla_analysis BOOLEAN NOT NULL DEFAULT true,
  include_resource_analysis BOOLEAN NOT NULL DEFAULT true,
  include_client_analysis BOOLEAN NOT NULL DEFAULT true,
  include_recommendations BOOLEAN NOT NULL DEFAULT true,
  created_at TIMESTAMP NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
  CONSTRAINT single_config CHECK (id = 1)
);

CREATE TABLE IF NOT EXISTS ticket_digest_webhooks (
  id SERIAL PRIMARY KEY,
  label VARCHAR(200) NOT NULL,
  webhook_url TEXT NOT NULL,
  digest_types TEXT[] NOT NULL DEFAULT '{daily,weekly,monthly}',
  enabled BOOLEAN NOT NULL DEFAULT true,
  last_delivered_at TIMESTAMP,
  last_status VARCHAR(20),
  created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE TABLE IF NOT EXISTS ticket_digest_reports (
  id SERIAL PRIMARY KEY,
  period_type VARCHAR(10) NOT NULL, -- 'daily', 'weekly', 'monthly'
  period_start TIMESTAMP NOT NULL,
  period_end TIMESTAMP NOT NULL,
  generated_at TIMESTAMP NOT NULL DEFAULT NOW(),
  stats JSONB NOT NULL DEFAULT '{}',
  llm_analysis TEXT,
  card_payload JSONB,
  delivery_status JSONB DEFAULT '{}',
  tokens_used INTEGER,
  processing_time_ms INTEGER,
  created_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_ticket_digest_reports_period ON ticket_digest_reports(period_type, period_start DESC);

-- Insert default config
INSERT INTO ticket_digest_config (id) VALUES (1) ON CONFLICT (id) DO NOTHING;
