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

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

    schema.description = new fields.HTMLField({ required: true, textSearch: true })

    // Proficiency group: light / medium / heavy (p.88)
    schema.armorType = new fields.StringField({ required: true, initial: "light", choices: SYSTEM.ARMOR_TYPE_CHOICES })

    // Armor Value (AV): number of armor dice rolled when receiving damage
    schema.armorValue = new fields.NumberField({ ...requiredInteger, initial: 0, min: 0, max: 16 })

    // Penalty: modifier to Acrobatics checks AND defense rolls (0, -1, -2, -3…)
    schema.penalty = new fields.NumberField({ ...requiredInteger, initial: 0, min: -5, max: 0 })

    // Item slots occupied while worn or stowed
    schema.slots = new fields.NumberField({ ...requiredInteger, initial: 0, min: 0 })

    // Armor traits: Clanging (−1 Stealth) / Reinforced (red dice for armor rolls)
    schema.traits = new fields.SetField(
      new fields.StringField({ choices: SYSTEM.ARMOR_TRAITS })
    )

    schema.rarity = new fields.StringField({ required: true, initial: "common", choices: SYSTEM.RARITY_CHOICES })

    schema.equipped = new fields.BooleanField({ initial: false })
    schema.cost = new fields.NumberField({ required: true, nullable: false, initial: 0, min: 0 })
    schema.currency = new fields.StringField({ required: true, initial: "gp", choices: SYSTEM.CURRENCY_CHOICES })

    // --- Magic properties (only relevant when isMagic = true) ---
    schema.isMagic      = new fields.BooleanField({ initial: false })
    schema.magicQuality = new fields.StringField({
      required: false, nullable: true, initial: null, choices: SYSTEM.MAGIC_QUALITY_CHOICES
    })
    schema.isCursed     = new fields.BooleanField({ initial: false })
    schema.magicEffect  = new fields.HTMLField({ required: false, textSearch: true })
    // Class/lineage restriction, e.g. "Dwarves only" (empty = no restriction)
    schema.classRestriction = new fields.StringField({ required: true, nullable: false, initial: "" })

    return schema
  }

  static migrateData(source) {
    if (typeof source.rarity === "number") {
      const map = { 0: "common", 1: "uncommon", 2: "rare", 3: "very-rare", 4: "legendary", 5: "legendary", 6: "legendary" }
      source.rarity = map[source.rarity] ?? "common"
    }
    return super.migrateData(source)
  }

  static LOCALIZATION_PREFIXES = ["OATHHAMMER.Armor"]
}
