-- Fase 9: recordatorios avanzados (segundo recordatorio + tracking + bitácora)

ALTER TABLE business_settings
  ADD COLUMN second_reminder_enabled TINYINT(1) NOT NULL DEFAULT 0 AFTER reminder_enabled,
  ADD COLUMN second_reminder_minutes SMALLINT UNSIGNED NOT NULL DEFAULT 120 AFTER second_reminder_enabled,
  ADD COLUMN tpl_second_reminder TEXT NULL AFTER tpl_reminder;

ALTER TABLE appointments
  ADD COLUMN second_reminded_at DATETIME NULL AFTER reminded_at,
  ADD COLUMN reminder_attempts  SMALLINT UNSIGNED NOT NULL DEFAULT 0 AFTER second_reminded_at,
  ADD COLUMN last_reminder_error VARCHAR(255) NULL AFTER reminder_attempts;

CREATE TABLE IF NOT EXISTS reminder_log (
  id             BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  business_id    INT UNSIGNED NOT NULL,
  appointment_id INT UNSIGNED NOT NULL,
  kind           ENUM('first','second') NOT NULL,
  status         ENUM('sent','failed') NOT NULL,
  provider_id    VARCHAR(191) NULL,
  error          VARCHAR(500) NULL,
  created_at     DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  INDEX idx_rl_biz (business_id, created_at),
  INDEX idx_rl_ap  (appointment_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
