-- Migration Script: Fix Schema Inconsistencies

-- Step 1: Migrate data from `categories` to `ticket_categories`
DO $$
BEGIN
    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'categories') THEN
        INSERT INTO ticket_categories (id, tenant_id, name, description)
        SELECT id, COALESCE(tenant_id, (SELECT id FROM tenants LIMIT 1)), name, description
        FROM categories;
    END IF;
END $$;

-- Step 2: Update foreign key for `tickets.category_id`
ALTER TABLE tickets DROP CONSTRAINT IF EXISTS tickets_category_id_fkey;
ALTER TABLE tickets ADD CONSTRAINT tickets_category_id_fkey FOREIGN KEY (category_id) REFERENCES ticket_categories (id) ON DELETE CASCADE;

-- Step 3: Drop `categories` table
DROP TABLE IF EXISTS categories CASCADE;

-- Step 4: Rename `tickets.system_id` to `affected_system_id`
DO $$
BEGIN
    IF EXISTS (
        SELECT 1 FROM information_schema.columns 
        WHERE table_name = 'tickets' AND column_name = 'system_id'
    ) THEN
        ALTER TABLE tickets RENAME COLUMN system_id TO affected_system_id;
    END IF;
END $$;

-- Step 5: Update foreign key for `tickets.affected_system_id`
ALTER TABLE tickets DROP CONSTRAINT IF EXISTS tickets_system_id_fkey;
ALTER TABLE tickets ADD CONSTRAINT tickets_affected_system_id_fkey FOREIGN KEY (affected_system_id) REFERENCES affected_systems (id) ON DELETE CASCADE;

-- Step 6: Create indexes for performance
CREATE INDEX IF NOT EXISTS idx_tickets_category_id ON tickets (category_id);
CREATE INDEX IF NOT EXISTS idx_tickets_affected_system_id ON tickets (affected_system_id);