-- Migration 142: Mission Control dashboard foundation

CREATE TABLE IF NOT EXISTS mission_events (
    id BIGSERIAL PRIMARY KEY,
    event_type VARCHAR(64) NOT NULL,
    severity VARCHAR(16) NOT NULL DEFAULT 'info',
    title VARCHAR(255) NOT NULL,
    source VARCHAR(64),
    customer_name VARCHAR(255),
    payload JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE INDEX IF NOT EXISTS idx_mission_events_created_at ON mission_events(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_mission_events_event_type ON mission_events(event_type);

CREATE TABLE IF NOT EXISTS mission_call_state (
    call_id VARCHAR(128) PRIMARY KEY,
    queue_name VARCHAR(128),
    caller_number VARCHAR(64),
    contact_name VARCHAR(255),
    company_name VARCHAR(255),
    customer_tag VARCHAR(64),
    state VARCHAR(32) NOT NULL,
    started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    answered_at TIMESTAMP,
    ended_at TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    last_payload JSONB NOT NULL DEFAULT '{}'::jsonb
);

CREATE INDEX IF NOT EXISTS idx_mission_call_state_state ON mission_call_state(state);
CREATE INDEX IF NOT EXISTS idx_mission_call_state_updated_at ON mission_call_state(updated_at DESC);

CREATE TABLE IF NOT EXISTS mission_uptime_alerts (
    alert_key VARCHAR(255) PRIMARY KEY,
    service_name VARCHAR(255) NOT NULL,
    customer_name VARCHAR(255),
    status VARCHAR(32) NOT NULL,
    is_active BOOLEAN NOT NULL DEFAULT FALSE,
    started_at TIMESTAMP,
    resolved_at TIMESTAMP,
    updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    raw_payload JSONB NOT NULL DEFAULT '{}'::jsonb,
    normalized_payload JSONB NOT NULL DEFAULT '{}'::jsonb
);

CREATE INDEX IF NOT EXISTS idx_mission_uptime_active ON mission_uptime_alerts(is_active, updated_at DESC);

INSERT INTO settings (key, value, category, description, value_type, is_public)
VALUES
    ('mission_webhook_token', '', 'mission', 'Shared token for mission webhooks', 'string', false),
    ('mission_display_queues', '[]', 'mission', 'JSON array of queue names shown on Mission Control', 'json', true),
    ('mission_sound_enabled', 'true', 'mission', 'Enable sound notifications on Mission Control', 'boolean', true),
    ('mission_sound_volume', '70', 'mission', 'Mission Control sound volume (0-100)', 'integer', true),
    ('mission_sound_events', '["incoming_call","uptime_down","critical_event"]', 'mission', 'JSON array of event types that trigger sound', 'json', true),
    ('mission_kpi_visible', '["open_cases","new_cases","unassigned_cases","deadlines_today","overdue_deadlines"]', 'mission', 'JSON array of KPI keys shown on Mission Control', 'json', true),
    ('mission_customer_filter', '', 'mission', 'Optional customer filter for Mission Control', 'string', true)
ON CONFLICT (key) DO NOTHING;
