ALTER TABLE sales_communication_sessions ADD COLUMN 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 source_type TEXT;
ALTER TABLE sales_notes ADD COLUMN source_id TEXT;
ALTER TABLE sales_notes ADD COLUMN updated_at TEXT;
ALTER TABLE sales_notes ADD COLUMN 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 assigned_at TEXT;
ALTER TABLE sales_escalations ADD COLUMN started_at TEXT;
ALTER TABLE sales_escalations ADD COLUMN canceled_at TEXT;
ALTER TABLE sales_escalations ADD COLUMN resolution_code TEXT;
ALTER TABLE sales_escalations ADD COLUMN resolution_summary TEXT;
ALTER TABLE sales_escalations ADD COLUMN sla_due_at TEXT;
ALTER TABLE sales_escalations ADD COLUMN source_channel TEXT;
ALTER TABLE sales_escalations ADD COLUMN source_communication_session_id TEXT;
ALTER TABLE sales_escalations ADD COLUMN source_automation_task_id TEXT;
ALTER TABLE sales_escalations ADD COLUMN 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 communication_session_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN previous_communication_session_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN new_communication_session_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN reason_code TEXT DEFAULT 'human_decision';
ALTER TABLE sales_channel_switches ADD COLUMN reason_text TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN initiated_by_type TEXT DEFAULT 'human';
ALTER TABLE sales_channel_switches ADD COLUMN initiated_by_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN source_type TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN source_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN recommended_by_task_id TEXT;
ALTER TABLE sales_channel_switches ADD COLUMN 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) = '';
