/// <reference path="../pb_data/types.d.ts" />
// One-shot data migration: rewrite legacy "executes" relations to the
// canonical "executed_by" vocabulary by swapping source and target.
// Previously `role --executes--> process`; canonical is
// `process --executed_by--> role`.
migrate((app) => {
  const records = app.findRecordsByFilter(
    "pbc_1883724256",  // relations collection
    'type = "executes"',
    '',
    0,
    0,
  )

  for (const rec of records) {
    const source = rec.get("source")
    const target = rec.get("target")
    rec.set("type", "executed_by")
    rec.set("source", target)
    rec.set("target", source)
    app.save(rec)
  }
}, (app) => {
  // Reverse: turn executed_by back into executes (best-effort — only those
  // created before this migration would have been "executes"; rolling back
  // will affect any newer executed_by rows too).
  const records = app.findRecordsByFilter(
    "pbc_1883724256",
    'type = "executed_by"',
    '',
    0,
    0,
  )

  for (const rec of records) {
    const source = rec.get("source")
    const target = rec.get("target")
    rec.set("type", "executes")
    rec.set("source", target)
    rec.set("target", source)
    app.save(rec)
  }
})
