-- Migration 031: align incidents table with AutoHeal ORM
-- Created: 2026-05-05 Asia/Taipei
--
-- Context:
-- - Existing production DB was created from migration 013 with error_traceback,
--   playbook_id and severity VARCHAR(5).
-- - database/autoheal_models.py now writes traceback_str, matched_playbook_id
--   and severity values such as "medium".
-- - Keep the old columns for backward compatibility and add the ORM columns
--   additively so running services do not need a destructive migration.

BEGIN;

ALTER TABLE incidents
    ADD COLUMN IF NOT EXISTS traceback_str TEXT;

ALTER TABLE incidents
    ADD COLUMN IF NOT EXISTS matched_playbook_id INTEGER;

ALTER TABLE incidents
    ALTER COLUMN severity TYPE VARCHAR(20);

UPDATE incidents
SET traceback_str = error_traceback
WHERE traceback_str IS NULL
  AND error_traceback IS NOT NULL;

UPDATE incidents
SET matched_playbook_id = playbook_id
WHERE matched_playbook_id IS NULL
  AND playbook_id IS NOT NULL;

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_constraint
        WHERE conname = 'incidents_matched_playbook_id_fkey'
    ) THEN
        ALTER TABLE incidents
            ADD CONSTRAINT incidents_matched_playbook_id_fkey
            FOREIGN KEY (matched_playbook_id)
            REFERENCES playbooks(id);
    END IF;
END $$;

COMMIT;
