// SPDX-FileCopyrightText: 2022 Johannes Loher
//
// SPDX-License-Identifier: MIT

import {
  getSceneMigrator,
  migrateCollection,
  migrateCompendiums,
  getCompendiumMigrator,
  getActorMigrator,
  getItemMigrator,
} from "./migrationHelpers.js";

/** @type {import("./migration.js").Migration["migrate"]} */
async function migrate() {
  const itemsResult = await migrateCollection(game.items, migrateItem);
  const actorsResult = await migrateCollection(game.actors, migrateActor);
  const scenesResult = await migrateCollection(game.scenes, migrateScene);
  const compendiumsResult = await migrateCompendiums(migrateCompendium);
  return itemsResult === "error" ||
    actorsResult === "error" ||
    scenesResult === "error" ||
    compendiumsResult === "error"
    ? "error"
    : "success";
}

/** @type {import('./migrationHelpers.js').Migrator<ActiveEffect>} */
async function migrateActiveEffect(activeEffect) {
  const data = activeEffect.toObject();
  let hasUpdates = false;

  if ("changes" in data) {
    for (const change of data.changes) {
      const newValue = change.value.replaceAll(/@data\./g, "@system.");
      if (newValue !== change.value) {
        hasUpdates = true;
        change.value = newValue;
      }
    }
  }

  /** @type {string | undefined} */
  const condition = data.flags?.ds4?.itemEffectConfig?.condition;
  if (condition !== undefined) {
    const newCondition = condition.replaceAll(/(@actor|@item|@effect)\.data/g, "$1.system");
    if (newCondition !== condition) {
      hasUpdates = true;
      data.flags.ds4.itemEffectConfig.condition = newCondition;
    }
  }
  if (hasUpdates) {
    await activeEffect.update(data);
  }
}

const migrateItem = getItemMigrator(migrateActiveEffect);
const migrateActor = getActorMigrator(migrateItem, migrateActiveEffect);
const migrateScene = getSceneMigrator(migrateActor);
const migrateCompendium = getCompendiumMigrator({ migrateItem, migrateActor, migrateScene });

/** @type {import("./migration.js").Migration} */
export const migration = {
  migrate,
  migrateCompendium,
};
