const n = require('./nocodb');
const OLD_ID = 6;
const NEW_ID = 1;

const TABLES_AND_FIELDS = [
  { table: 'Posts', fields: ['assigned_to_id', 'created_by_user_id'] },
  { table: 'Tasks', fields: ['assigned_to_id', 'created_by_user_id'] },
  { table: 'Projects', fields: ['owner_id', 'created_by_user_id'] },
  { table: 'Campaigns', fields: ['created_by_user_id'] },
  { table: 'Assets', fields: ['uploader_id'] },
  { table: 'Comments', fields: ['user_id'] },
  { table: 'CampaignAssignments', fields: ['member_id', 'assigner_id'] },
  { table: 'Artefacts', fields: ['created_by_user_id'] },
  { table: 'ArtefactVersions', fields: ['created_by_user_id'] },
  { table: 'Issues', fields: ['assigned_to_id'] },
  { table: 'TeamMembers', fields: ['user_id'] },
  { table: 'BudgetEntries', fields: [] },
];

(async () => {
  for (const { table, fields } of TABLES_AND_FIELDS) {
    for (const field of fields) {
      try {
        const records = await n.list(table, { where: `(${field},eq,${OLD_ID})`, limit: 200 });
        if (records.length === 0) continue;
        console.log(`${table}.${field}: ${records.length} records to update`);
        for (const r of records) {
          await n.update(table, r.Id, { [field]: NEW_ID });
        }
        console.log(`  -> done`);
      } catch (err) {
        console.log(`${table}.${field}: skipped (${err.message})`);
      }
    }
  }
  console.log('Reassignment complete.');
})();
