-- Ajustes incrementais para performance do modulo de chamados
SET @db = DATABASE();

SET @sql = IF(
    EXISTS (
        SELECT 1 FROM information_schema.statistics
        WHERE table_schema = @db
          AND table_name = 'chamados'
          AND index_name = 'idx_chamados_status_prioridade_data_abertura'
    ),
    'SELECT 1',
    'ALTER TABLE chamados ADD INDEX idx_chamados_status_prioridade_data_abertura (status, prioridade, data_abertura)'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @sql = IF(
    EXISTS (
        SELECT 1 FROM information_schema.statistics
        WHERE table_schema = @db
          AND table_name = 'chamados'
          AND index_name = 'idx_chamados_cliente_status'
    ),
    'SELECT 1',
    'ALTER TABLE chamados ADD INDEX idx_chamados_cliente_status (cliente_id, status)'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @sql = IF(
    EXISTS (
        SELECT 1 FROM information_schema.statistics
        WHERE table_schema = @db
          AND table_name = 'chamados_mensagens'
          AND index_name = 'idx_chamados_mensagens_chamado_data'
    ),
    'SELECT 1',
    'ALTER TABLE chamados_mensagens ADD INDEX idx_chamados_mensagens_chamado_data (chamado_id, data_criacao)'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;

SET @sql = IF(
    EXISTS (
        SELECT 1 FROM information_schema.statistics
        WHERE table_schema = @db
          AND table_name = 'chamados_historicos'
          AND index_name = 'idx_chamados_historicos_chamado_data'
    ),
    'SELECT 1',
    'ALTER TABLE chamados_historicos ADD INDEX idx_chamados_historicos_chamado_data (chamado_id, data_criacao)'
);
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
