-- Migration v87: Correção tipo_fila + pa_habilitado
-- Segura para rodar mesmo se v86 já foi aplicada parcialmente
-- Compatível com MariaDB 10.x e MySQL 8.x

-- ─────────────────────────────────────────────────────────────────────────────
-- 1. Garante que tipo_fila existe em fila_atendimento com DEFAULT correto
-- ─────────────────────────────────────────────────────────────────────────────
SET @col_exists = (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME   = 'fila_atendimento'
      AND COLUMN_NAME  = 'tipo_fila'
);

-- Adiciona a coluna se não existir
SET @sql = IF(@col_exists = 0,
    'ALTER TABLE fila_atendimento ADD COLUMN tipo_fila ENUM(''pa'',''agendamento'') NOT NULL DEFAULT ''agendamento'' AFTER clinica_id',
    'SELECT ''tipo_fila ja existe'' AS info'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- Corrige o DEFAULT caso já exista com valor errado ('pa')
SET @sql2 = IF(@col_exists > 0,
    'ALTER TABLE fila_atendimento MODIFY COLUMN tipo_fila ENUM(''pa'',''agendamento'') NOT NULL DEFAULT ''agendamento''',
    'SELECT ''coluna criada com default correto'' AS info'
);
PREPARE stmt FROM @sql2; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- Índice — só adiciona se ainda não existir
SET @idx_exists = (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME   = 'fila_atendimento'
      AND INDEX_NAME   = 'idx_fila_tipo'
);
SET @sql_idx = IF(@idx_exists = 0,
    'ALTER TABLE fila_atendimento ADD INDEX idx_fila_tipo (tipo_fila)',
    'SELECT ''idx_fila_tipo ja existe'' AS info'
);
PREPARE stmt FROM @sql_idx; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- ─────────────────────────────────────────────────────────────────────────────
-- 2. Garante que vezes_chamado existe
-- ─────────────────────────────────────────────────────────────────────────────
SET @col2 = (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME   = 'fila_atendimento'
      AND COLUMN_NAME  = 'vezes_chamado'
);
SET @sql3 = IF(@col2 = 0,
    'ALTER TABLE fila_atendimento ADD COLUMN vezes_chamado SMALLINT UNSIGNED NOT NULL DEFAULT 0 AFTER chamado_recepcao_em',
    'SELECT ''vezes_chamado ja existe'' AS info'
);
PREPARE stmt FROM @sql3; EXECUTE stmt; DEALLOCATE PREPARE stmt;

-- ─────────────────────────────────────────────────────────────────────────────
-- 3. Corrige tickets existentes: todos os que foram criados pelo totem
--    (sem tipo_fila definido) devem ser 'agendamento', não 'pa'
--    Não altera tickets que já foram manualmente classificados como 'pa'
-- ─────────────────────────────────────────────────────────────────────────────
UPDATE fila_atendimento
SET tipo_fila = 'agendamento'
WHERE tipo_fila = 'pa'
  AND deleted_at IS NULL;

-- ─────────────────────────────────────────────────────────────────────────────
-- 4. pa_habilitado na tabela correta (configuracoes)
-- ─────────────────────────────────────────────────────────────────────────────
INSERT INTO configuracoes (chave, valor, descricao, tipo)
VALUES (
    'pa_habilitado',
    '0',
    'Habilitar módulo de Pronto Atendimento (PA) com fila e triagem',
    'booleano'
)
ON DUPLICATE KEY UPDATE descricao = VALUES(descricao);

-- ─────────────────────────────────────────────────────────────────────────────
-- 5. Permissão fila_gerenciar (se não existe)
-- ─────────────────────────────────────────────────────────────────────────────
INSERT IGNORE INTO permissoes (nome, chave, descricao)
VALUES ('Fila — Gerenciar', 'fila_gerenciar', 'Cancelar senhas e gerenciar fila de atendimento');

-- Perfil Admin (1) e Recepcionista (3) recebem fila_gerenciar
INSERT IGNORE INTO perfil_permissoes (perfil_id, permissao_id)
SELECT p.id, perm.id
FROM perfis p, permissoes perm
WHERE p.id IN (1, 3)
  AND perm.chave = 'fila_gerenciar';

SELECT 'Migration v87 aplicada com sucesso.' AS resultado;
