-- =====================================================================
-- AI Front Desk Platform — Migration 011
--
-- Separates two distinct durations that were being conflated under one
-- column:
--   - calls.duration_seconds (existing, unchanged) — the TOTAL inbound
--     leg duration: from call.initiated to the caller's own hangup.
--     This includes AI conversation time AND ringback/wait time during
--     a transfer attempt, whether or not that transfer ever connected.
--     Correctly shows e.g. 45s for a caller who hung up mid-ringback —
--     that IS how long they were actually on the line.
--   - agent_connected_at / agent_disconnected_at / agent_talk_duration_seconds
--     (new) — the AGENT-CONNECTED portion specifically: only populated
--     once a transfer's bridge() call actually succeeds, i.e. a human
--     agent was genuinely on the line with the caller. Stays NULL for
--     any call that was never transferred, or where the transfer was
--     attempted but the caller hung up (or bridging failed) before an
--     agent connected — exactly the "ringing but never connected"
--     case this distinction exists to separate out.
--
-- Single-attempt columns rather than a separate call_transfers table —
-- matches the platform's current single-route Phase 1 behavior (no
-- retry on a failed/no-answer transfer, see telnyx-outbound.php's
-- no_answer_no_failover handling). Revisit as a proper child table if
-- multi-attempt transfer retries are ever added — these columns can
-- only represent one transfer attempt's connected window per call.
-- =====================================================================

SET NAMES utf8mb4;

ALTER TABLE calls
    ADD COLUMN agent_connected_at DATETIME NULL
        COMMENT 'Set once a transfer bridge() call succeeds — a human agent was actually on the line with the caller. NULL if never transferred, or transfer attempted but never connected.'
        AFTER duration_seconds,
    ADD COLUMN agent_disconnected_at DATETIME NULL
        COMMENT 'Set when the AGENT leg''s own call.hangup fires, only if agent_connected_at was already set.'
        AFTER agent_connected_at,
    ADD COLUMN agent_talk_duration_seconds INT UNSIGNED NULL
        COMMENT 'agent_disconnected_at - agent_connected_at, in seconds. NULL whenever agent_connected_at is NULL (never connected).'
        AFTER agent_disconnected_at;
