/// <reference path="../pb_data/types.d.ts" />
migrate(
  app => {
    const appearanceColId = 'pbc_4190072853';
    let scoresCol = app.findCollectionByNameOrId('scores');

    if (!scoresCol.fields.fieldNames().includes('appearance')) {
      scoresCol.fields.addAt(scoresCol.fields.length, new Field({
        cascadeDelete: false,
        collectionId: appearanceColId,
        hidden: false,
        id: 'relation8849102734',
        maxSelect: 1,
        minSelect: 0,
        name: 'appearance',
        presentable: false,
        required: false,
        system: false,
        type: 'relation'
      }));
      app.save(scoresCol);
      scoresCol = app.findCollectionByNameOrId('scores');
    }

    const pageSize = 200;
    let offset = 0;
    while (true) {
      const batch = app.findRecordsByFilter(scoresCol.id, '', '', pageSize, offset);
      if (batch.length === 0) {
        break;
      }
      for (const record of batch) {
        let appearanceId = record.get('appearance');
        if (typeof appearanceId !== 'string' || appearanceId === '') {
          const entrantId = record.get('entrant');
          const sessionId = record.get('session');
          if (
            typeof entrantId === 'string' &&
            entrantId !== '' &&
            typeof sessionId === 'string' &&
            sessionId !== ''
          ) {
            const hits = app.findRecordsByFilter(
              appearanceColId,
              `entrant="${entrantId}" && session="${sessionId}"`,
              'order',
              1,
              0
            );
            if (hits.length > 0) {
              appearanceId = hits[0].id;
              record.set('appearance', appearanceId);
              app.save(record);
            }
          }
        }
      }
      offset += batch.length;
      if (batch.length < pageSize) {
        break;
      }
    }

    offset = 0;
    while (true) {
      const batch = app.findRecordsByFilter(scoresCol.id, '', '', pageSize, offset);
      if (batch.length === 0) {
        break;
      }
      for (const record of batch) {
        const appearanceId = record.get('appearance');
        if (typeof appearanceId !== 'string' || appearanceId === '') {
          app.delete(record);
        }
      }
      offset += batch.length;
      if (batch.length < pageSize) {
        break;
      }
    }

    scoresCol = app.findCollectionByNameOrId('scores');
    if (scoresCol.fields.fieldNames().includes('entrant')) {
      scoresCol.fields.removeByName('entrant');
    }
    if (scoresCol.fields.fieldNames().includes('session')) {
      scoresCol.fields.removeByName('session');
    }

    const appearanceField = scoresCol.fields.getByName('appearance');
    if (appearanceField) {
      appearanceField.required = true;
      appearanceField.minSelect = 1;
    }

    return app.save(scoresCol);
  },
  app => {
    const appearanceColId = 'pbc_4190072853';
    let scoresCol = app.findCollectionByNameOrId('scores');

    const appearanceField = scoresCol.fields.getByName('appearance');
    if (appearanceField) {
      appearanceField.required = false;
      appearanceField.minSelect = 0;
    }

    if (!scoresCol.fields.fieldNames().includes('entrant')) {
      scoresCol.fields.addAt(1, new Field({
        cascadeDelete: false,
        collectionId: 'pbc_918751319',
        hidden: false,
        id: 'relation1542800728',
        maxSelect: 1,
        minSelect: 0,
        name: 'entrant',
        presentable: false,
        required: false,
        system: false,
        type: 'relation'
      }));
    }
    if (!scoresCol.fields.fieldNames().includes('session')) {
      scoresCol.fields.addAt(2, new Field({
        cascadeDelete: false,
        collectionId: 'pbc_1092069950',
        hidden: false,
        id: 'relation3494172116',
        maxSelect: 1,
        minSelect: 0,
        name: 'session',
        presentable: false,
        required: false,
        system: false,
        type: 'relation'
      }));
    }
    app.save(scoresCol);
    scoresCol = app.findCollectionByNameOrId('scores');

    let offset = 0;
    const pageSize = 200;
    while (true) {
      const batch = app.findRecordsByFilter(scoresCol.id, '', '', pageSize, offset);
      if (batch.length === 0) {
        break;
      }
      for (const record of batch) {
        const appearanceId = record.get('appearance');
        if (typeof appearanceId === 'string' && appearanceId !== '') {
          try {
            const appRecord = app.findRecordById(appearanceColId, appearanceId);
            record.set('entrant', appRecord.get('entrant'));
            record.set('session', appRecord.get('session'));
            app.save(record);
          } catch {
            // appearance missing — leave entrant/session empty
          }
        }
      }
      offset += batch.length;
      if (batch.length < pageSize) {
        break;
      }
    }

    return app.save(scoresCol);
  }
);
