/**
 * Chroniques de l'Étrange — Système FoundryVTT
 *
 * Chroniques de l'Étrange est un jeu de rôle édité par Antre-Monde Éditions.
 * Ce système FoundryVTT est une implémentation indépendante et n'est pas
 * affilié à Antre-Monde Éditions,
 * mais a été réalisé avec l'autorisation d'Antre-Monde Éditions.
 *
 * @author    LeRatierBretonnien
 * @copyright 2024–2026 LeRatierBretonnien
 * @license   CC BY-NC-SA 4.0 – https://creativecommons.org/licenses/by-nc-sa/4.0/
 */

import { SYSTEM_ID } from "./constants.js"
import { CDEMigrationApp } from "../ui/apps/migration-app.js"

/**
 * Register all world/client settings for the system.
 * Called during the "init" hook before sheets and data-models are set up.
 */
export function registerSettings() {
  game.settings.registerMenu(SYSTEM_ID, "migrationTool", {
    name: "CDE.MigrationTitle",
    label: "CDE.MigrationMenuLabel",
    hint: "CDE.MigrationMenuHint",
    icon: "fas fa-file-import",
    type: CDEMigrationApp,
    restricted: true,
  })

  game.settings.register(SYSTEM_ID, "loksyuData", {
    scope: "world",
    config: false,
    type: Object,
    default: {
      wood:  { yin: 0, yang: 0 },
      fire:  { yin: 0, yang: 0 },
      earth: { yin: 0, yang: 0 },
      metal: { yin: 0, yang: 0 },
      water: { yin: 0, yang: 0 },
    },
  })

  game.settings.register(SYSTEM_ID, "loksyuConsumptionOrder", {
    name: "CDE.Settings.LoksyuConsumptionOrder",
    hint: "CDE.Settings.LoksyuConsumptionOrderHint",
    scope: "world",
    config: true,
    type: String,
    choices: {
      "yang-first": "CDE.Settings.LoksyuOrderYangFirst",
      "yin-first": "CDE.Settings.LoksyuOrderYinFirst",
      "balanced": "CDE.Settings.LoksyuOrderBalanced",
    },
    default: "yang-first",
    onChange: () => Hooks.callAll("cde:loksyuUpdated"),
  })

  game.settings.register(SYSTEM_ID, "tinjiData", {
    scope: "world",
    config: false,
    type: Number,
    default: 0,
  })

  game.settings.register(SYSTEM_ID, "welcomeSceneLoaded", {
    scope: "world",
    config: false,
    type: Boolean,
    default: false,
  })
}

/**
 * Run any pending data migrations on the "ready" hook.
 * Reserved for future schema migrations.
 */
export async function migrateIfNeeded() {
  // No migrations required yet.
}

/**
 * On first startup, import the "Accueil" scene from the cde-scenes compendium
 * into the world and activate it. Only runs once (tracked via the
 * `welcomeSceneLoaded` setting). GM-only.
 */
export async function loadWelcomeSceneIfNeeded() {
  if (!game.user.isGM) return
  if (game.settings.get(SYSTEM_ID, "welcomeSceneLoaded")) return

  try {
    const pack = game.packs.get(`${SYSTEM_ID}.cde-scenes`)
    if (!pack) return

    const index = await pack.getIndex()
    const entry = index.find(e => e.name === "Accueil")
    if (!entry) return

    // Check if the scene already exists in the world (e.g. manually imported)
    const existing = game.scenes.find(s => s.name === "Accueil")
    let scene = existing

    if (!scene) {
      const doc = await pack.getDocument(entry._id)
      ;[scene] = await Scene.createDocuments([doc.toObject()])
    }

    await game.settings.set(SYSTEM_ID, "welcomeSceneLoaded", true)
    await scene.activate()
  } catch (err) {
    console.error("CHRONIQUESDELETRANGE | loadWelcomeSceneIfNeeded failed:", err)
  }
}
