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

    // Add preVarScore if missing.
    if (!scoresCol.fields.fieldNames().includes('preVarScore')) {
      scoresCol.fields.addAt(scoresCol.fields.length, new Field({
        hidden: false,
        id: 'number_preVarScore',
        max: null,
        min: null,
        name: 'preVarScore',
        onlyInt: false,
        presentable: false,
        required: false,
        system: false,
        type: 'number',
      }));
    }

    // Remove legacy fields that are now derivable (appearance via appearanceSong.appearance).
    if (scoresCol.fields.fieldNames().includes('appearance')) {
      scoresCol.fields.removeByName('appearance');
    }
    if (scoresCol.fields.fieldNames().includes('timestamp')) {
      scoresCol.fields.removeByName('timestamp');
    }

    return app.save(scoresCol);
  },
  app => {
    const scoresCol = app.findCollectionByNameOrId('pbc_809716240');

    if (scoresCol.fields.fieldNames().includes('preVarScore')) {
      scoresCol.fields.removeByName('preVarScore');
    }

    // Restore removed fields (best-effort; old clients may rely on them).
    const appearanceColId = 'pbc_4190072853';
    if (!scoresCol.fields.fieldNames().includes('appearance')) {
      scoresCol.fields.addAt(scoresCol.fields.length, new Field({
        cascadeDelete: false,
        collectionId: appearanceColId,
        hidden: false,
        id: 'relation_appearance_legacy',
        maxSelect: 1,
        minSelect: 0,
        name: 'appearance',
        presentable: false,
        required: false,
        system: false,
        type: 'relation',
      }));
    }

    if (!scoresCol.fields.fieldNames().includes('timestamp')) {
      scoresCol.fields.addAt(scoresCol.fields.length, new Field({
        hidden: false,
        id: 'date_timestamp_legacy',
        max: '',
        min: '',
        name: 'timestamp',
        presentable: false,
        required: false,
        system: false,
        type: 'date',
      }));
    }

    return app.save(scoresCol);
  }
);

