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

export default class PrismRPGShield 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 })

    // Prism RPG shield properties
    schema.shieldType = new fields.StringField({
      required: true,
      initial: "buckler",
      choices: SYSTEM.SHIELD_TYPE_CHOICES
    })

    // APC (Action Point Cost) for Block action
    schema.apc = new fields.NumberField({
      ...requiredInteger,
      required: true,
      initial: 1,
      min: 1,
      max: 4,
      label: "Block APC"
    })

    // Shield Rating (SR) - damage prevention dice (e.g., "1d4", "1d8", "1d12", "3d6")
    schema.sr = new fields.StringField({
      required: true,
      initial: "1d4",
      label: "Shield Rating (SR)"
    })

    // Block Augment - passive ability when using Block action
    schema.blockAugment = new fields.StringField({
      required: true,
      initial: "",
      label: "Block Augment"
    })

    schema.blockAugmentDescription = new fields.HTMLField({
      required: true,
      initial: "",
      label: "Block Augment Description"
    })

    // Augment effects (for equipment progression)
    schema.augment = new fields.StringField({
      required: true,
      initial: "",
      label: "Shield Augment"
    })

    schema.augmentDescription = new fields.HTMLField({
      required: true,
      initial: "",
      label: "Augment Description"
    })

    // Equipment properties
    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({ 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 })

    return schema
  }

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

  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 shield: Invalid money type "${data.money}", defaulting to coppercoin`)
        data.money = "coppercoin"
      }
    }

    return super.migrateData(data)
  }
}
