CREATE TABLE IF NOT EXISTS case_type_catalog (
  id BIGSERIAL PRIMARY KEY,
  code VARCHAR(50) UNIQUE NOT NULL,
  label VARCHAR(120) NOT NULL,
  sort_order INTEGER NOT NULL DEFAULT 100,
  is_active BOOLEAN NOT NULL DEFAULT TRUE,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

INSERT INTO case_type_catalog (code, label, sort_order)
VALUES
  ('anhoerung', 'Anhörung', 10),
  ('beschwerde', 'Beschwerde', 20),
  ('einstellung', 'Einstellung', 30),
  ('kuendigung', 'Kündigung', 40),
  ('personalmassnahme', 'Personalmaßnahme', 50),
  ('versetzung', 'Versetzung', 60),
  ('sonstiges', 'Sonstiges', 999)
ON CONFLICT (code) DO NOTHING;

INSERT INTO case_type_catalog (code, label, sort_order)
SELECT DISTINCT
  LOWER(REGEXP_REPLACE(TRIM(case_type), '[^a-zA-Z0-9]+', '_', 'g')) AS code,
  TRIM(case_type) AS label,
  500
FROM br_case
WHERE case_type IS NOT NULL
  AND TRIM(case_type) <> ''
ON CONFLICT (code) DO NOTHING;

ALTER TABLE br_case
  ADD COLUMN IF NOT EXISTS case_type_id BIGINT REFERENCES case_type_catalog(id);

UPDATE br_case c
SET case_type_id = ct.id
FROM case_type_catalog ct
WHERE c.case_type_id IS NULL
  AND c.case_type IS NOT NULL
  AND TRIM(c.case_type) <> ''
  AND LOWER(REGEXP_REPLACE(TRIM(c.case_type), '[^a-zA-Z0-9]+', '_', 'g')) = ct.code;

UPDATE br_case
SET case_type_id = (
  SELECT id FROM case_type_catalog WHERE code = 'sonstiges'
)
WHERE case_type_id IS NULL;

ALTER TABLE br_case
  ALTER COLUMN case_type_id SET NOT NULL;

ALTER TABLE br_case
  ALTER COLUMN priority SET DEFAULT 'mittel';
