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

const CREATURE_TYPES = ["human", "construct", "animal"]

export default class MGNECreature extends foundry.abstract.TypeDataModel {
  static defineSchema() {
    const fields = foundry.data.fields

    return {
      hp: trackSchema(1, 1),
      morale: numberField(7, 2, 12),
      armor: new fields.SchemaField({
        die: new fields.StringField({ required: true, nullable: false, initial: "0", choices: SYSTEM.armorDieChoices }),
      }),
      creatureType: new fields.SetField(
        new fields.StringField({ required: true, choices: CREATURE_TYPES }),
        { required: true, nullable: false, initial: [] }
      ),
      number: stringField("1"),
      actionTableUuid: stringField(""),
      description: htmlField(""),
    }
  }

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

  /** @override */
  static migrateData(source) {
    // Remove old attack field if present (no longer part of the schema)
    if ("attack" in source) delete source.attack
    // Form submissions send null for unchecked checkboxes in array fields — filter them out
    if (Array.isArray(source.creatureType)) {
      source.creatureType = source.creatureType.filter(v => v != null && v !== "")
    }
    return super.migrateData(source)
  }
}
