-- Ensure Treatment feature and permissions exist for existing databases.
WITH treatment_feature AS (
  INSERT INTO "features" ("id", "name")
  VALUES (md5(random()::text || clock_timestamp()::text), 'Treatment')
  ON CONFLICT ("name") DO UPDATE SET "name" = EXCLUDED."name"
  RETURNING "id"
),
selected_feature AS (
  SELECT "id" FROM treatment_feature
  UNION ALL
  SELECT f."id" FROM "features" f WHERE f."name" = 'Treatment' LIMIT 1
)
INSERT INTO "permissions" ("id", "name", "featureId")
SELECT md5(random()::text || clock_timestamp()::text), 'TAB_TREATMENT_READ', sf."id"
FROM selected_feature sf
ON CONFLICT ("name") DO NOTHING;

WITH treatment_feature AS (
  SELECT "id" FROM "features" WHERE "name" = 'Treatment' LIMIT 1
)
INSERT INTO "permissions" ("id", "name", "featureId")
SELECT md5(random()::text || clock_timestamp()::text), 'TAB_TREATMENT_EDIT', tf."id"
FROM treatment_feature tf
ON CONFLICT ("name") DO NOTHING;
