///|
fn optional_object(
  value : Json?,
  name : String,
) -> Map[String, Json] raise ContractError {
  match value {
    None => Map([])
    Some(raw) => object(raw, name)
  }
}

///|
priv struct Migration {
  renames : Map[String, String]
  defaults : Map[String, Json]
  drops : Map[String, Bool]
}

///|
fn read_migration(
  raw : Json,
  source : Contract,
  target : Contract,
) -> Migration raise ContractError {
  let spec = object(raw, "migration")
  keys(spec, ["rename", "defaults", "drop"])
  let renames = optional_object(spec.get("rename"), "rename")
  let defaults = optional_object(spec.get("defaults"), "defaults")
  if renames.length() > 64 || defaults.length() > 64 {
    raise ContractError("migration accepts at most 64 renames and 64 defaults")
  }
  let moves : Map[String, String] = Map([])
  let destinations : Map[String, Bool] = Map([])
  for name in renames.keys() {
    guard renames[name] is String(dest) &&
      name != dest &&
      source.fields.contains(name) &&
      target.fields.contains(dest) else {
      raise ContractError(
        "rename must link distinct declared source and target fields: " + name,
      )
    }
    if destinations.contains(dest) {
      raise ContractError("duplicate rename destination: " + dest)
    }
    moves[name] = dest
    destinations[dest] = true
  }
  for name in defaults.keys() {
    guard target.fields.get(name) is Some(field) &&
      accepts(field.domain, defaults[name]) else {
      raise ContractError(
        "default must match its declared target field: " + name,
      )
    }
  }
  let drops : Map[String, Bool] = Map([])
  if spec.get("drop") is Some(drop) {
    guard drop is Array(names) && names.length() <= 64 else {
      raise ContractError("drop must be an array of at most 64 field names")
    }
    for raw_name in names {
      guard raw_name is String(name) &&
        source.fields.contains(name) &&
        !target.fields.contains(name) else {
        raise ContractError("drop must name a retired source field")
      }
      if moves.contains(name) {
        raise ContractError("cannot drop and rename the same field: " + name)
      }
      if drops.contains(name) {
        raise ContractError("duplicate drop field: " + name)
      }
      drops[name] = true
    }
  }
  { renames: moves, defaults, drops, }
}

///|
fn check_entry(code : String, position : Int32, details : Json) -> Json {
  Json::object(
    Map([
      ("index", Json::number(position.to_double())),
      ("outcome", Json::string(code)),
      ("details", details),
    ]),
  )
}

///|
fn migration_issues(items : Array[Violation]) -> Json {
  Json::array(
    items.map(item => {
      Json::object(
        Map([
          ("field", Json::string(item.field)),
          ("reason", Json::string(item.reason)),
        ]),
      )
    }),
  )
}

///|
fn rehearse(request : Map[String, Json]) -> (Json, Bool) raise ContractError {
  keys(request, ["mode", "source", "target", "migration", "records"])
  guard request.get("source") is Some(old_schema) &&
    request.get("target") is Some(new_schema) &&
    request.get("migration") is Some(migration) &&
    request.get("records") is Some(Array(records)) &&
    records.length() > 0 &&
    records.length() <= 256 else {
    raise ContractError(
      "rehearse requires source, target, migration and 1..256 records",
    )
  }
  let source = parse_contract(old_schema)
  let target = parse_contract(new_schema)
  let { renames, defaults, drops, } = read_migration(migration, source, target)
  let default_names : Array[String] = []
  for name in defaults.keys() {
    default_names.push(name)
  }
  default_names.sort()
  let mut passed = 0
  let entries = records.mapi((i, record) => {
    let source_issues = validate(source, record)
    if !source_issues.is_empty() {
      return check_entry("source_rejected", i, migration_issues(source_issues))
    }
    guard record is Object(original) else {
      abort("validated record must be an object")
    }
    let changed : Map[String, Json] = Map([])
    let original_names : Array[String] = []
    for name in original.keys() {
      original_names.push(name)
    }
    original_names.sort()
    for name in original_names {
      if drops.contains(name) {
        continue
      }
      let to = renames.get(name).unwrap_or(name)
      if changed.contains(to) {
        return check_entry("rename_collision", i, Json::string(to))
      }
      changed[to] = original[name]
    }
    for name in default_names {
      if !changed.contains(name) {
        changed[name] = defaults[name]
      }
    }
    let updated = Json::object(changed)
    let target_issues = validate(target, updated)
    if !target_issues.is_empty() {
      return check_entry("target_rejected", i, migration_issues(target_issues))
    }
    passed += 1
    check_entry("ready", i, updated)
  })
  let all_ready = passed == records.length()
  (
    Json::object(
      Map([
        ("ready", Json::boolean(all_ready)),
        ("passed", Json::number(passed.to_double())),
        ("total", Json::number(records.length().to_double())),
        ("records", Json::array(entries)),
      ]),
    ),
    all_ready,
  )
}