-- Migration v99: Módulo de Evolução do Paciente (Saúde Inteligente)
-- Camada de inteligência sobre resultados_online e bs_resultados
-- Execute no banco: clinica_encaminhamento

-- ─────────────────────────────────────────────────────────────────────────────
-- Métricas de saúde extraídas por OCR + HealthParser
-- ─────────────────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS `ep_metricas_saude` (
  `id`              int(11)       NOT NULL AUTO_INCREMENT,
  `paciente_id`     int(11)       NOT NULL,
  `documento_tipo`  enum('resultado_online','bs_resultado') NOT NULL DEFAULT 'resultado_online',
  `documento_id`    int(11)       NOT NULL COMMENT 'FK para resultados_online.id OU bs_resultados.id',
  `parametro`       varchar(100)  NOT NULL COMMENT 'ex: hemoglobina, glicose, colesterol_total',
  `parametro_label` varchar(120)  NOT NULL COMMENT 'ex: Hemoglobina, Glicose em Jejum',
  `valor`           decimal(12,3) NOT NULL,
  `unidade`         varchar(30)   DEFAULT NULL COMMENT 'ex: g/dL, mg/dL, U/L',
  `referencia_min`  decimal(12,3) DEFAULT NULL,
  `referencia_max`  decimal(12,3) DEFAULT NULL,
  `referencia_texto` varchar(100) DEFAULT NULL COMMENT 'texto original do VR quando min/max não extraíveis',
  `status_valor`    enum('normal','alto','baixo','critico_alto','critico_baixo') NOT NULL DEFAULT 'normal',
  `data_exame`      date          NOT NULL,
  `texto_contexto`  varchar(500)  DEFAULT NULL COMMENT 'linha do laudo onde foi encontrado',
  `created_at`      timestamp     NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `idx_ep_metrica_paciente`   (`paciente_id`, `parametro`, `data_exame`),
  KEY `idx_ep_metrica_documento`  (`documento_tipo`, `documento_id`),
  KEY `idx_ep_metrica_status`     (`status_valor`),
  CONSTRAINT `fk_ep_metrica_paciente` FOREIGN KEY (`paciente_id`) REFERENCES `pacientes` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Parâmetros de saúde extraídos por OCR/parser dos documentos';

-- ─────────────────────────────────────────────────────────────────────────────
-- Alertas inteligentes gerados pelo engine de análise
-- ─────────────────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS `ep_alertas` (
  `id`              int(11)       NOT NULL AUTO_INCREMENT,
  `paciente_id`     int(11)       NOT NULL,
  `tipo`            enum('exame_atrasado','valor_critico','diagnostico_pendente','preventivo') NOT NULL,
  `urgencia`        enum('urgente','atencao','preventivo') NOT NULL DEFAULT 'preventivo',
  `titulo`          varchar(255)  NOT NULL,
  `descricao`       text          DEFAULT NULL,
  `status`          enum('pendente','enviado','ignorado','resolvido') NOT NULL DEFAULT 'pendente',
  `canal_envio`     enum('whatsapp_oficial','whatsapp_evolution','email','nenhum') DEFAULT NULL,
  `data_disparo`    datetime      DEFAULT NULL,
  `dados_contexto`  json          DEFAULT NULL COMMENT 'contexto extra: ultimo_exame, parametro, cid, dias_atraso',
  `criado_por_engine` tinyint(1)  NOT NULL DEFAULT 1 COMMENT '1=engine automático, 0=admin manual',
  `created_at`      timestamp     NOT NULL DEFAULT current_timestamp(),
  `updated_at`      timestamp     NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `idx_ep_alerta_paciente` (`paciente_id`, `status`),
  KEY `idx_ep_alerta_tipo`     (`tipo`, `urgencia`),
  CONSTRAINT `fk_ep_alerta_paciente` FOREIGN KEY (`paciente_id`) REFERENCES `pacientes` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Alertas inteligentes de saúde por paciente';

-- ─────────────────────────────────────────────────────────────────────────────
-- Log de cada notificação enviada
-- ─────────────────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS `ep_notificacoes` (
  `id`              int(11)       NOT NULL AUTO_INCREMENT,
  `alerta_id`       int(11)       NOT NULL,
  `paciente_id`     int(11)       NOT NULL,
  `canal`           enum('whatsapp_oficial','whatsapp_evolution','email') NOT NULL,
  `numero_destino`  varchar(20)   DEFAULT NULL,
  `mensagem`        text          DEFAULT NULL,
  `status`          enum('enviado','falha','pendente') NOT NULL DEFAULT 'pendente',
  `resposta_api`    text          DEFAULT NULL,
  `created_at`      timestamp     NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `idx_ep_notif_alerta`   (`alerta_id`),
  KEY `idx_ep_notif_paciente` (`paciente_id`),
  CONSTRAINT `fk_ep_notif_alerta`   FOREIGN KEY (`alerta_id`)   REFERENCES `ep_alertas`  (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_ep_notif_paciente` FOREIGN KEY (`paciente_id`) REFERENCES `pacientes`   (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Log de envio de notificações de saúde';

-- ─────────────────────────────────────────────────────────────────────────────
-- Configurações do módulo (singleton — sempre um único registro)
-- ─────────────────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS `ep_config` (
  `id`                           int(11)  NOT NULL AUTO_INCREMENT,
  `canal_whatsapp`               enum('oficial','evolution','desativado') NOT NULL DEFAULT 'evolution',
  `dias_sem_exame_atencao`       int(11)  NOT NULL DEFAULT 90  COMMENT 'Dias sem exame → alerta atenção',
  `dias_sem_exame_urgente`       int(11)  NOT NULL DEFAULT 180 COMMENT 'Dias sem exame → alerta urgente',
  `dias_diagnostico_pendente`    int(11)  NOT NULL DEFAULT 60  COMMENT 'Dias com CID aberto sem acompanhamento',
  `tpl_exame_atrasado`           text     DEFAULT NULL COMMENT 'Template WA: {nome}, {dias}, {link}',
  `tpl_valor_critico`            text     DEFAULT NULL COMMENT 'Template WA: {nome}, {parametro}, {valor}, {link}',
  `tpl_diagnostico_pendente`     text     DEFAULT NULL COMMENT 'Template WA: {nome}, {cid}, {dias}, {link}',
  `engine_ativo`                 tinyint(1) NOT NULL DEFAULT 1 COMMENT 'Liga/desliga engine de alertas',
  `updated_at`                   timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Configuração singleton do módulo de evolução do paciente';

INSERT INTO `ep_config`
  (`canal_whatsapp`, `dias_sem_exame_atencao`, `dias_sem_exame_urgente`, `dias_diagnostico_pendente`,
   `tpl_exame_atrasado`, `tpl_valor_critico`, `tpl_diagnostico_pendente`, `engine_ativo`)
VALUES
  ('evolution', 90, 180, 60,
   'Olá {nome}! 👋 Notamos que faz {dias} dias que você não realiza exames de acompanhamento. Cuide da sua saúde! Acesse seu histórico: {link}',
   'Olá {nome}! ⚠️ Em seu último exame, o parâmetro *{parametro}* apresentou valor {valor} fora da referência. Converse com seu médico. Acesse: {link}',
   'Olá {nome}! Identificamos que há {dias} dias foi registrado em seu prontuário o CID *{cid}* que ainda aguarda acompanhamento. Agende uma consulta. Acesse: {link}',
   1);

-- ─────────────────────────────────────────────────────────────────────────────
-- Controla quais documentos já foram processados pelo OCR+Parser
-- ─────────────────────────────────────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS `ep_ocr_processados` (
  `id`             int(11)      NOT NULL AUTO_INCREMENT,
  `documento_tipo` enum('resultado_online','bs_resultado') NOT NULL,
  `documento_id`   int(11)      NOT NULL,
  `status`         enum('pendente','processando','concluido','erro','sem_dados') NOT NULL DEFAULT 'pendente',
  `metricas_extraidas` smallint(5) NOT NULL DEFAULT 0 COMMENT 'Qtd de métricas salvas',
  `erro_msg`       varchar(500) DEFAULT NULL,
  `processado_em`  datetime     DEFAULT NULL,
  `created_at`     timestamp    NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `uq_ep_ocr_doc` (`documento_tipo`, `documento_id`),
  KEY `idx_ep_ocr_status` (`status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
  COMMENT='Rastreia status do OCR por documento';

-- ─────────────────────────────────────────────────────────────────────────────
-- Permissões
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO `permissoes` (`nome`, `chave`, `descricao`) VALUES
  ('Evolução Paciente - Visualizar',   'evolucao_paciente_view',    'Visualizar dashboards e timelines de evolução de saúde dos pacientes'),
  ('Evolução Paciente - Processar OCR','evolucao_paciente_ocr',     'Processar documentos via OCR e extrair métricas de saúde'),
  ('Evolução Paciente - Alertas',      'evolucao_paciente_alertas', 'Gerenciar e disparar alertas inteligentes de saúde')
ON DUPLICATE KEY UPDATE `nome` = VALUES(`nome`), `descricao` = VALUES(`descricao`);

-- Garante que perfil admin (id=1) tenha as permissões
INSERT IGNORE INTO `perfil_permissoes` (`perfil_id`, `permissao_id`)
SELECT 1, `id` FROM `permissoes`
WHERE `chave` IN ('evolucao_paciente_view','evolucao_paciente_ocr','evolucao_paciente_alertas');
