-- Add database indexes for performance optimization
-- Check and create index on tickets.status
SET @index_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
                     WHERE TABLE_NAME = 'tickets'
                     AND INDEX_NAME = 'idx_status'
                     AND TABLE_SCHEMA = DATABASE());

SET @sql = IF(@index_exists = 0,
  'CREATE INDEX idx_status ON tickets(status)',
  'SELECT "Index idx_status already exists"');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Check and create index on tickets.priority
SET @index_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
                     WHERE TABLE_NAME = 'tickets'
                     AND INDEX_NAME = 'idx_priority'
                     AND TABLE_SCHEMA = DATABASE());

SET @sql = IF(@index_exists = 0,
  'CREATE INDEX idx_priority ON tickets(priority)',
  'SELECT "Index idx_priority already exists"');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Check and create index on tickets.created_at
SET @index_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
                     WHERE TABLE_NAME = 'tickets'
                     AND INDEX_NAME = 'idx_tickets_created_at'
                     AND TABLE_SCHEMA = DATABASE());

SET @sql = IF(@index_exists = 0,
  'CREATE INDEX idx_tickets_created_at ON tickets(created_at)',
  'SELECT "Index idx_tickets_created_at already exists"');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
