-- Migration 005: Bugtracker Push ID, Target Agent, Tags, and Extended Severities (idea, wishlist)
-- Non-destructive migration

SET FOREIGN_KEY_CHECKS = 0;

-- 1. Extend ENUM severity column if needed or modify column definition
ALTER TABLE bugtracker_items 
  MODIFY COLUMN severity ENUM('idea', 'wishlist', 'low', 'medium', 'high', 'critical') NOT NULL DEFAULT 'medium';

-- 2. Add push_id column if not exists
SET @exist_push_id := (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'bugtracker_items' 
      AND COLUMN_NAME = 'push_id'
);
SET @sql_push_id := IF(@exist_push_id = 0, 'ALTER TABLE bugtracker_items ADD COLUMN push_id VARCHAR(128) NULL AFTER occurrence_count, ADD KEY ix_bt_push_id (push_id);', 'SELECT 1;');
PREPARE stmt FROM @sql_push_id;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 3. Add target_agent column if not exists
SET @exist_target_agent := (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'bugtracker_items' 
      AND COLUMN_NAME = 'target_agent'
);
SET @sql_target_agent := IF(@exist_target_agent = 0, 'ALTER TABLE bugtracker_items ADD COLUMN target_agent VARCHAR(100) NULL AFTER push_id;', 'SELECT 1;');
PREPARE stmt FROM @sql_target_agent;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- 4. Add tags column if not exists
SET @exist_tags := (
    SELECT COUNT(*) 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
      AND TABLE_NAME = 'bugtracker_items' 
      AND COLUMN_NAME = 'tags'
);
SET @sql_tags := IF(@exist_tags = 0, 'ALTER TABLE bugtracker_items ADD COLUMN tags VARCHAR(255) NULL AFTER target_agent;', 'SELECT 1;');
PREPARE stmt FROM @sql_tags;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

SET FOREIGN_KEY_CHECKS = 1;

-- Seed Deployment Center Project
INSERT INTO dc_projects (id, slug, name, notes, default_cache_ttl_hours) VALUES
(4, 'deploymentcenter', 'Deployment Center', 'Zentrale Verwaltungs- & Update-Plattform', 168)
ON DUPLICATE KEY UPDATE name = VALUES(name);

-- Seed Sample Feature Idea
INSERT IGNORE INTO bugtracker_items (
  id, project_slug, type, title, description, error_message, stack_trace, error_hash, build_version, environment, severity, status, occurrence_count, push_id, target_agent, tags, created_by
) VALUES
(4, 'myapp', 'feature_request', 'Automatische Datenbank-Backups vor Deployments', 'Idee für später: Vor jedem FTP-Deployment automatisch einen Mysqldump ausführen und im Server-Archiv ablegen.', NULL, NULL, NULL, 'v1.6.0-idea', 'development', 'idea', 'open', 1, 'push_notify_99182', 'agent:dev-monitor-01', 'database,automation', 'user:richard');
