CREATE TABLE citas (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  odontologo_id BIGINT UNSIGNED NOT NULL,
  paciente_id BIGINT UNSIGNED NOT NULL,
  inicio DATETIME NOT NULL,
  fin DATETIME NOT NULL,
  estado ENUM('programada','cancelada','completada') NOT NULL DEFAULT 'programada',
  motivo VARCHAR(255) NULL,
  creado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_citas_odontologo FOREIGN KEY (odontologo_id) REFERENCES odontologos(id),
  CONSTRAINT fk_citas_paciente FOREIGN KEY (paciente_id) REFERENCES pacientes(id),
  CONSTRAINT chk_citas_rango CHECK (fin > inicio),
  KEY idx_citas_odontologo_inicio_estado (odontologo_id, inicio, estado),
  KEY idx_citas_paciente_inicio (paciente_id, inicio)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE plantillas_recordatorio (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  odontologo_id BIGINT UNSIGNED NOT NULL,
  nombre VARCHAR(100) NOT NULL,
  contenido TEXT NOT NULL,
  activa TINYINT(1) NOT NULL DEFAULT 1,
  creado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  actualizado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  CONSTRAINT fk_plantillas_odontologo FOREIGN KEY (odontologo_id) REFERENCES odontologos(id),
  KEY idx_plantillas_odontologo_activa (odontologo_id, activa)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE recordatorios (
  id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
  odontologo_id BIGINT UNSIGNED NOT NULL,
  paciente_id BIGINT UNSIGNED NOT NULL,
  cita_id BIGINT UNSIGNED NOT NULL,
  plantilla_id BIGINT UNSIGNED NULL,
  canal ENUM('whatsapp_enlace') NOT NULL DEFAULT 'whatsapp_enlace',
  contenido TEXT NOT NULL,
  clave_idempotencia CHAR(64) NOT NULL,
  estado ENUM('preparado','enlace_abierto','cancelado') NOT NULL DEFAULT 'preparado',
  creado_en DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
  abierto_en DATETIME NULL,
  CONSTRAINT fk_recordatorios_odontologo FOREIGN KEY (odontologo_id) REFERENCES odontologos(id),
  CONSTRAINT fk_recordatorios_paciente FOREIGN KEY (paciente_id) REFERENCES pacientes(id),
  CONSTRAINT fk_recordatorios_cita FOREIGN KEY (cita_id) REFERENCES citas(id),
  CONSTRAINT fk_recordatorios_plantilla FOREIGN KEY (plantilla_id) REFERENCES plantillas_recordatorio(id),
  UNIQUE KEY uq_recordatorios_idempotencia (clave_idempotencia),
  KEY idx_recordatorios_cita_estado (cita_id, estado)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
