-- SPDX-FileCopyrightText: 2024 Simon Bruder <simon@sbruder.de>
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

DROP TRIGGER prevent_item_class_recursion ON item_classes;
DROP FUNCTION check_item_class_parent;

ALTER TABLE item_classes
  DROP CONSTRAINT parent_only_for_specific;

ALTER TABLE item_classes
  DROP type;

DROP TYPE item_class_type;

CREATE FUNCTION check_item_class_recursion_depth()
RETURNS TRIGGER AS $$
BEGIN
  IF NEW.parent IS NULL THEN
    RETURN NEW;
  END IF;

  IF (SELECT parent FROM item_classes WHERE id = NEW.parent) IS NULL THEN
    RETURN NEW;
  END IF;

  RAISE EXCEPTION 'Item classes may only be nested one level deep';
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER prevent_item_class_recursion
BEFORE INSERT OR UPDATE ON item_classes
FOR EACH ROW
EXECUTE FUNCTION check_item_class_recursion_depth();
