import type { Database } from 'bun:sqlite';

import { tableHasColumn } from './helpers.js';
import type { SchemaMigrationDefinition } from './types.js';

export const ARBITER_INTERVENTION_COUNT_MIGRATION: SchemaMigrationDefinition = {
  version: 20,
  name: 'arbiter_intervention_count',
  apply(database: Database) {
    if (
      !tableHasColumn(database, 'paired_tasks', 'arbiter_intervention_count')
    ) {
      database.exec(`
        ALTER TABLE paired_tasks
        ADD COLUMN arbiter_intervention_count INTEGER NOT NULL DEFAULT 0
      `);
    }

    database.exec(`
      UPDATE paired_tasks
         SET arbiter_intervention_count = 0
       WHERE arbiter_intervention_count IS NULL
    `);
  },
};
