import { SYSTEM } from "../config/system.mjs"

export default class PrismRPGEquipment extends foundry.abstract.TypeDataModel {
  static defineSchema() {
    const fields = foundry.data.fields
    const schema = {}
    const requiredInteger = { required: true, nullable: false, integer: true }

    schema.description = new fields.HTMLField({ required: true, textSearch: true })
    schema.category = new fields.StringField({ required: true, initial: "coppercoin", choices: SYSTEM.EQUIPMENT_CATEGORIES })

    schema.quantity = new fields.NumberField({ ...requiredInteger, initial: 1, min: 1 })
    schema.encLoad = new fields.NumberField({ required: true, initial: 0, min: 0 })
    schema.cost = new fields.NumberField({ ...requiredInteger, required: true, initial: 0, min: 0 })
    schema.money = new fields.StringField({ required: true, initial: "coppercoin", choices: SYSTEM.MONEY })
    schema.equipped = new fields.BooleanField({ required: true, initial: false })
    schema.containerId = new fields.StringField({ required: false, initial: "", nullable: false })

    // Kit properties
    schema.isKit = new fields.BooleanField({
      required: true,
      initial: false,
      label: "Is Kit"
    })

    // Kit passive (only applies when isKit is true)
    schema.passive = new fields.StringField({
      required: false,
      initial: "",
      label: "Passive Name"
    })

    schema.passiveDescription = new fields.HTMLField({
      required: false,
      initial: "",
      label: "Passive Description"
    })

    // Special Activations (only applies when isKit is true)
    schema.specialActivations = new fields.ArrayField(new fields.SchemaField({
      name: new fields.StringField({
        required: true,
        initial: ""
      }),
      description: new fields.HTMLField({
        required: true,
        initial: ""
      })
    }), {
      required: true,
      initial: []
    })

    return schema
  }

  /** @override */
  static LOCALIZATION_PREFIXES = ["PRISMRPG.Equipment"]

  static migrateData(data) {
    // Migrate old money types to new ones
    if (data?.money) {
      const moneyMigration = {
        "tinbit": "coppercoin",
        "copper": "coppercoin",
        "silver": "silvercoin",
        "gold": "goldcoin",
        "platinum": "note"
      }
      
      if (moneyMigration[data.money]) {
        data.money = moneyMigration[data.money]
      }
      
      // If still invalid, default to coppercoin
      if (!SYSTEM.MONEY[data.money]) {
        console.warn(`Prism RPG | Migrate equipment: Invalid money type "${data.money}", defaulting to coppercoin`)
        data.money = "coppercoin"
      }
    }

    return super.migrateData(data)
  }

}
