import { SYSTEM } from "../config/system.mjs"
import { booleanField, htmlField, numberField, stringField } from "./shared.mjs"

export default class MGNEWeapon extends foundry.abstract.TypeDataModel {
  static defineSchema() {
    return {
      description: htmlField(""),
      category: new foundry.data.fields.StringField({
        required: true,
        nullable: false,
        initial: "melee",
        choices: SYSTEM.weaponCategories,
      }),
      damage: stringField("1d4"),
      range: stringField("Touch"),
      properties: new foundry.data.fields.SetField(
        new foundry.data.fields.StringField({ required: true, nullable: false, blank: false }),
        { required: true, nullable: false, initial: [] }
      ),
      weight: new foundry.data.fields.StringField({
        required: true, nullable: false, initial: "normal",
        choices: SYSTEM.weightCategories,
      }),
      usageDie: new foundry.data.fields.StringField({
        required: true,
        nullable: false,
        initial: "d6",
        choices: SYSTEM.usageDieChoices,
      }),
      quantity: numberField(1, 0),
      equipped: booleanField(false),
      broken: booleanField(false),
      durabilityDie: new foundry.data.fields.StringField({
        required: true, nullable: false, initial: "d6",
        choices: SYSTEM.usageDieChoices,
      }),
    }
  }

  /** @override */
  static LOCALIZATION_PREFIXES = ["MGNE.Weapon"]

  /**
   * Migrate old string-based properties field to the new SetField format.
   * @override
   */
  static migrateData(source) {
    // Old data stored properties as a plain string; convert to empty array
    if (typeof source.properties === "string") {
      source.properties = []
    }
    // Remove any null/undefined/blank entries that may have crept in
    if (Array.isArray(source.properties)) {
      source.properties = source.properties.filter(p => p != null && p !== "")
    }
    return super.migrateData(source)
  }
}
