/// <reference path="../pb_data/types.d.ts" />
// Adds per-user curriculum enrollment fields to team_members:
//   - curriculum_started_at: datetime the user started their 26-week cycle
//   - enrollment_status: 'not_started' | 'active'
// Existing rows are reset to 'not_started' so every user re-enrolls via the
// onboarding screen on next login. All progress (micro-learning completions
// and leaderboard standings) is hard-reset so everyone restarts from week 1.
migrate((app) => {
  const tm = app.findCollectionByNameOrId("team_members");

  tm.fields.add(new Field({
    "hidden": false,
    "id": "date_curriculum_started_at",
    "name": "curriculum_started_at",
    "presentable": false,
    "required": false,
    "system": false,
    "type": "date"
  }));

  tm.fields.add(new Field({
    "autogeneratePattern": "",
    "hidden": false,
    "id": "text_enrollment_status",
    "max": 0,
    "min": 0,
    "name": "enrollment_status",
    "pattern": "",
    "presentable": false,
    "primaryKey": false,
    "required": false,
    "system": false,
    "type": "text"
  }));

  app.save(tm);

  // Reset everyone to not_started — they re-enroll via the onboarding screen.
  const members = app.findRecordsByFilter("team_members", "id != ''", "", 0, 0);
  for (const rec of members) {
    rec.set("enrollment_status", "not_started");
    rec.set("curriculum_started_at", "");
    app.save(rec);
  }

  // Hard-reset all progress so everyone genuinely restarts from week 1.
  for (const name of ["micro_learning_completions", "leaderboard"]) {
    const coll = app.findCollectionByNameOrId(name);
    if (!coll) continue;
    const rows = app.findRecordsByFilter(name, "id != ''", "", 0, 0);
    for (const row of rows) {
      app.delete(row);
    }
  }
}, (app) => {
  const tm = app.findCollectionByNameOrId("team_members");
  tm.fields.removeById("date_curriculum_started_at");
  tm.fields.removeById("text_enrollment_status");
  app.save(tm);
});
