-- Add user tracking columns to tickets table
ALTER TABLE tickets
  ADD COLUMN IF NOT EXISTS created_by INT,
  ADD COLUMN IF NOT EXISTS updated_by INT,
  ADD COLUMN IF NOT EXISTS updated_at TIMESTAMP NULL;

-- Add foreign key constraints if they don't exist
SET @fk_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
                  WHERE CONSTRAINT_NAME = 'fk_tickets_created_by'
                  AND TABLE_NAME = 'tickets'
                  AND TABLE_SCHEMA = DATABASE());

SET @sql = IF(@fk_exists = 0,
  'ALTER TABLE tickets ADD CONSTRAINT fk_tickets_created_by FOREIGN KEY (created_by) REFERENCES users(user_id) ON DELETE SET NULL',
  'SELECT "Foreign key fk_tickets_created_by already exists"');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET @fk_exists = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
                  WHERE CONSTRAINT_NAME = 'fk_tickets_updated_by'
                  AND TABLE_NAME = 'tickets'
                  AND TABLE_SCHEMA = DATABASE());

SET @sql = IF(@fk_exists = 0,
  'ALTER TABLE tickets ADD CONSTRAINT fk_tickets_updated_by FOREIGN KEY (updated_by) REFERENCES users(user_id) ON DELETE SET NULL',
  'SELECT "Foreign key fk_tickets_updated_by already exists"');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
