ALTER TABLE sales_communication_sessions ADD COLUMN IF NOT EXISTS channel_provider TEXT;
CREATE INDEX IF NOT EXISTS idx_sales_comm_channel_provider ON sales_communication_sessions(channel_provider);

ALTER TABLE sales_notes ADD COLUMN IF NOT EXISTS source_type TEXT;
ALTER TABLE sales_notes ADD COLUMN IF NOT EXISTS source_id TEXT;
ALTER TABLE sales_notes ADD COLUMN IF NOT EXISTS updated_at TEXT;
ALTER TABLE sales_notes ADD COLUMN IF NOT EXISTS archived_at TEXT;
UPDATE sales_notes
SET updated_at = created_at
WHERE updated_at IS NULL OR TRIM(updated_at) = '';

ALTER TABLE sales_escalations ADD COLUMN IF NOT EXISTS assigned_at TEXT;
ALTER TABLE sales_escalations ADD COLUMN IF NOT EXISTS started_at TEXT;
ALTER TABLE sales_escalations ADD COLUMN IF NOT EXISTS canceled_at TEXT;
ALTER TABLE sales_escalations ADD COLUMN IF NOT EXISTS resolution_code TEXT;
ALTER TABLE sales_escalations ADD COLUMN IF NOT EXISTS resolution_summary TEXT;
ALTER TABLE sales_escalations ADD COLUMN IF NOT EXISTS sla_due_at TEXT;
ALTER TABLE sales_escalations ADD COLUMN IF NOT EXISTS source_channel TEXT;
ALTER TABLE sales_escalations ADD COLUMN IF NOT EXISTS source_communication_session_id TEXT;
ALTER TABLE sales_escalations ADD COLUMN IF NOT EXISTS source_automation_task_id TEXT;
ALTER TABLE sales_escalations ADD COLUMN IF NOT EXISTS updated_at TEXT;
UPDATE sales_escalations
SET updated_at = COALESCE(updated_at, resolved_at, created_at)
WHERE updated_at IS NULL OR TRIM(updated_at) = '';

ALTER TABLE sales_channel_switches ADD COLUMN IF NOT EXISTS communication_session_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN IF NOT EXISTS previous_communication_session_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN IF NOT EXISTS new_communication_session_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN IF NOT EXISTS reason_code TEXT DEFAULT 'human_decision';
ALTER TABLE sales_channel_switches ADD COLUMN IF NOT EXISTS reason_text TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN IF NOT EXISTS initiated_by_type TEXT DEFAULT 'human';
ALTER TABLE sales_channel_switches ADD COLUMN IF NOT EXISTS initiated_by_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN IF NOT EXISTS source_type TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN IF NOT EXISTS source_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN IF NOT EXISTS recommended_by_task_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN IF NOT EXISTS created_at TEXT;
UPDATE sales_channel_switches
SET communication_session_id = COALESCE(communication_session_id, communication_id),
    previous_communication_session_id = COALESCE(previous_communication_session_id, communication_id),
    reason_code = COALESCE(reason_code, 'human_decision'),
    reason_text = COALESCE(reason_text, reason_for_channel_switch),
    initiated_by_type = COALESCE(initiated_by_type, 'human'),
    created_at = COALESCE(created_at, switched_at)
WHERE created_at IS NULL OR TRIM(created_at) = '';
