-- Migration v73: Glosas de Convênios

CREATE TABLE IF NOT EXISTS `faturamento_glosas` (
  `id`              int(11)      NOT NULL AUTO_INCREMENT,
  `clinica_id`      int(11)      NOT NULL,
  `numero_lote`     varchar(20)  DEFAULT NULL,
  `convenio_id`     int(11)      DEFAULT NULL,
  `paciente_id`     int(11)      DEFAULT NULL,
  `internacao_id`   int(11)      DEFAULT NULL,
  `agendamento_id`  int(11)      DEFAULT NULL,
  `competencia`     varchar(7)   DEFAULT NULL COMMENT 'YYYY-MM',
  `tipo_glosa`      ENUM('administrativa','tecnica','auditoria') NOT NULL DEFAULT 'administrativa',
  `codigo_glosa`    varchar(20)  DEFAULT NULL,
  `descricao`       varchar(300) NOT NULL,
  `valor_glosado`   decimal(10,2) NOT NULL DEFAULT 0.00,
  `valor_recorrido` decimal(10,2) DEFAULT NULL,
  `status`          ENUM('pendente','em_recurso','aceita','negada','parcial') NOT NULL DEFAULT 'pendente',
  `justificativa_recurso` text DEFAULT NULL,
  `resposta_convenio`     text DEFAULT NULL,
  `usuario_id`      int(11)      DEFAULT NULL,
  `responsavel_recurso_id` int(11) DEFAULT NULL,
  `data_glosa`      date         NOT NULL,
  `data_recurso`    date         DEFAULT NULL,
  `data_resposta`   date         DEFAULT NULL,
  `deleted_at`      datetime     DEFAULT NULL,
  `created_at`      datetime     DEFAULT current_timestamp(),
  `updated_at`      datetime     DEFAULT current_timestamp() ON UPDATE current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `idx_glosa_clinica`  (`clinica_id`, `status`),
  KEY `idx_glosa_convenio` (`convenio_id`),
  KEY `idx_glosa_data`     (`data_glosa`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci;

INSERT IGNORE INTO `permissoes` (`chave`, `nome`, `descricao`) VALUES
('glosas_view',     'Glosas — Visualizar',    'Visualizar glosas de convênios'),
('glosas_create',   'Glosas — Registrar',     'Registrar novas glosas'),
('glosas_recurso',  'Glosas — Recorrer',      'Abrir recurso de glosa');

INSERT IGNORE INTO `perfil_permissoes` (`perfil_id`, `permissao_id`)
SELECT p.id, pm.id FROM `perfis` p, `permissoes` pm
WHERE p.id IN (1,4) AND pm.chave IN ('glosas_view','glosas_create','glosas_recurso');
