/// <reference path="../pb_data/types.d.ts" />
migrate(
  app => {
    let col = app.findCollectionByNameOrId('scoring_judges');
    let names = col.fields.fieldNames();

    if (names.includes('isLuddite') && !names.includes('luddite')) {
      return app.save(col);
    }

    if (names.includes('isLuddite') && names.includes('luddite')) {
      col.fields.removeByName('luddite');
      return app.save(col);
    }

    const ludditeIdx = names.indexOf('luddite');
    const insertAt = ludditeIdx >= 0 ? ludditeIdx + 1 : col.fields.length;
    col.fields.addAt(
      insertAt,
      new Field({
        hidden: false,
        id: 'bool1779400001',
        name: 'isLuddite',
        presentable: false,
        required: false,
        system: false,
        type: 'bool'
      })
    );
    app.save(col);
    col = app.findCollectionByNameOrId('scoring_judges');

    const pageSize = 200;
    let offset = 0;
    while (true) {
      const batch = app.findRecordsByFilter(col.id, '', '', pageSize, offset);
      if (batch.length === 0) {
        break;
      }
      for (const record of batch) {
        record.set('isLuddite', record.get('luddite') === true);
        app.save(record);
      }
      offset += batch.length;
      if (batch.length < pageSize) {
        break;
      }
    }

    col = app.findCollectionByNameOrId('scoring_judges');
    if (col.fields.fieldNames().includes('luddite')) {
      col.fields.removeByName('luddite');
    }
    return app.save(col);
  },
  app => {
    let col = app.findCollectionByNameOrId('scoring_judges');
    let names = col.fields.fieldNames();

    if (names.includes('luddite') && !names.includes('isLuddite')) {
      return app.save(col);
    }

    if (!names.includes('luddite')) {
      col.fields.addAt(
        col.fields.length,
        new Field({
          hidden: false,
          id: 'bool1676545486',
          name: 'luddite',
          presentable: false,
          required: false,
          system: false,
          type: 'bool'
        })
      );
      app.save(col);
      col = app.findCollectionByNameOrId('scoring_judges');
    }

    const pageSize = 200;
    let offset = 0;
    while (true) {
      const batch = app.findRecordsByFilter(col.id, '', '', pageSize, offset);
      if (batch.length === 0) {
        break;
      }
      for (const record of batch) {
        record.set('luddite', record.get('isLuddite') === true);
        app.save(record);
      }
      offset += batch.length;
      if (batch.length < pageSize) {
        break;
      }
    }

    col = app.findCollectionByNameOrId('scoring_judges');
    if (col.fields.fieldNames().includes('isLuddite')) {
      col.fields.removeByName('isLuddite');
    }
    return app.save(col);
  }
);
