-- Tabla de métricas por llamada (call_metrics).
-- Se crea automáticamente al arrancar si CALL_METRICS_ENABLED=true.
-- Este archivo es referencia / migración manual.
-- Cada llamada = una fila nueva (nunca se actualizan costos de filas previas).

CREATE TABLE IF NOT EXISTS call_sessions (
  id BIGINT AUTO_INCREMENT PRIMARY KEY,
  call_id VARCHAR(64) NOT NULL,
  document_id VARCHAR(64) NULL,
  number VARCHAR(64) NULL,
  direction VARCHAR(16) NULL,
  start_time DATETIME(3) NULL,
  answer_time DATETIME(3) NULL,
  first_bot_audio_time DATETIME(3) NULL,
  end_time DATETIME(3) NULL,
  duration_seconds DOUBLE NULL,
  time_to_first_audio_ms INT NULL,
  user_turns INT NOT NULL DEFAULT 0,
  bot_turns INT NOT NULL DEFAULT 0,
  stt_requests INT NOT NULL DEFAULT 0,
  llm_requests INT NOT NULL DEFAULT 0,
  tts_requests INT NOT NULL DEFAULT 0,
  total_prompt_tokens INT NOT NULL DEFAULT 0,
  total_completion_tokens INT NOT NULL DEFAULT 0,
  stt_audio_seconds DOUBLE NOT NULL DEFAULT 0,
  tts_characters INT NOT NULL DEFAULT 0,
  estimated_cost DECIMAL(12,6) NOT NULL DEFAULT 0,
  avg_llm_latency_ms DOUBLE NULL,
  avg_tts_latency_ms DOUBLE NULL,
  avg_stt_latency_ms DOUBLE NULL,
  avg_response_latency_ms DOUBLE NULL,
  interruptions INT NOT NULL DEFAULT 0,
  silence_seconds DOUBLE NOT NULL DEFAULT 0,
  silence_percent DOUBLE NULL,
  disconnect_reason VARCHAR(255) NULL,
  turn_timings_json JSON NULL,
  providers_json JSON NULL,
  created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
  KEY idx_call_sessions_call_id (call_id),
  KEY idx_call_sessions_start_time (start_time),
  KEY idx_call_sessions_document (document_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Si la tabla ya existía con UNIQUE(call_id), ejecutá esto una vez:
-- ALTER TABLE call_sessions DROP INDEX uq_call_sessions_call_id;
