-- =====================================================
-- Migration v33: Módulo de Eleição
-- Integração completa ao sistema HSRB
-- =====================================================

-- Tabela de eleitores (separada dos usuários do sistema)
CREATE TABLE IF NOT EXISTS `eleicao_eleitores` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(200) NOT NULL,
  `cpf` varchar(14) NOT NULL COMMENT 'Apenas dígitos (11 chars)',
  `tipo_eleitor` enum('FUNCIONÁRIO','DIRETOR','ACIONISTA') NOT NULL DEFAULT 'FUNCIONÁRIO',
  `percentual` float NOT NULL DEFAULT 1 COMMENT 'Peso do voto',
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=ativo, 0=bloqueado',
  `senha` varchar(255) NOT NULL COMMENT 'bcrypt — nunca MD5',
  `data_cadastro` datetime NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_cpf` (`cpf`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Tabela de eleições
CREATE TABLE IF NOT EXISTS `eleicoes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `titulo` varchar(300) NOT NULL,
  `descricao` text DEFAULT NULL,
  `tipo_eleicao` varchar(100) DEFAULT NULL COMMENT 'Ex: CIPA, Conselho, Diretoria',
  `tipo_eleitor` enum('FUNCIONÁRIO','DIRETOR','ACIONISTA','TODOS') NOT NULL DEFAULT 'TODOS',
  `data_inicio` datetime NOT NULL,
  `data_fim` datetime NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT 1 COMMENT '1=aberta,2=andamento,3=finalizada',
  `criado_por` int(11) DEFAULT NULL COMMENT 'usuarios.id',
  `data_criacao` datetime NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `fk_eleicao_criador` (`criado_por`),
  CONSTRAINT `fk_eleicao_criador` FOREIGN KEY (`criado_por`) REFERENCES `usuarios` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Tabela de candidatos
CREATE TABLE IF NOT EXISTS `eleicao_candidatos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `eleicao_id` int(11) NOT NULL,
  `eleitor_id` int(11) NOT NULL,
  `numero` int(11) NOT NULL COMMENT 'Número de 2 dígitos (10-99)',
  `foto` varchar(300) DEFAULT NULL COMMENT 'Nome do arquivo em uploads/eleicao/',
  `qtd_votos` int(11) NOT NULL DEFAULT 0,
  `data_cadastro` datetime NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_eleicao_numero` (`eleicao_id`,`numero`),
  KEY `fk_cand_eleitor` (`eleitor_id`),
  CONSTRAINT `fk_cand_eleicao` FOREIGN KEY (`eleicao_id`) REFERENCES `eleicoes` (`id`) ON DELETE CASCADE,
  CONSTRAINT `fk_cand_eleitor` FOREIGN KEY (`eleitor_id`) REFERENCES `eleicao_eleitores` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Tabela de votos
-- UNIQUE KEY em (eleitor_id, eleicao_id) impede voto duplo no banco
CREATE TABLE IF NOT EXISTS `eleicao_votos` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `eleitor_id` int(11) NOT NULL,
  `candidato_id` int(11) NOT NULL,
  `eleicao_id` int(11) NOT NULL,
  `data_voto` datetime NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_eleitor_eleicao` (`eleitor_id`,`eleicao_id`),
  KEY `fk_voto_candidato` (`candidato_id`),
  KEY `fk_voto_eleicao` (`eleicao_id`),
  CONSTRAINT `fk_voto_candidato` FOREIGN KEY (`candidato_id`) REFERENCES `eleicao_candidatos` (`id`),
  CONSTRAINT `fk_voto_eleicao` FOREIGN KEY (`eleicao_id`) REFERENCES `eleicoes` (`id`),
  CONSTRAINT `fk_voto_eleitor` FOREIGN KEY (`eleitor_id`) REFERENCES `eleicao_eleitores` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

-- Permissões do módulo
INSERT INTO `permissoes` (`chave`, `nome`, `descricao`) VALUES
  ('eleicao_view',   'Ver Eleições',        'Permite acessar o painel administrativo de eleições'),
  ('eleicao_manage', 'Gerenciar Eleições',   'Permite criar/editar eleições, candidatos e eleitores')
ON DUPLICATE KEY UPDATE `nome` = VALUES(`nome`), `descricao` = VALUES(`descricao`);

-- Conceder ao perfil Administrador (id = 1)
INSERT IGNORE INTO `perfil_permissoes` (`perfil_id`, `permissao_id`)
  SELECT 1, `id` FROM `permissoes` WHERE `chave` IN ('eleicao_view', 'eleicao_manage');
