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

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

/**
 * Compatibility backfill for `turn_progress_text` (migration 015).
 *
 * Some deployments first shipped `reviewer_failure_count` as a local migration
 * numbered 15, so their `schema_migrations` table records version 15 under a
 * different name than the canonical `turn_progress_text` migration. The runner
 * skips migrations purely by version number, so on those databases the real
 * version-15 migration never runs and `paired_turns.progress_text` /
 * `progress_updated_at` are missing — yet the runtime reads them. This migration
 * re-adds the columns idempotently so collided databases converge with fresh
 * ones. On a fresh database migration 015 already created the columns, so the
 * `tableHasColumn` guards make this a no-op.
 */
export const TURN_PROGRESS_TEXT_COMPAT_MIGRATION: SchemaMigrationDefinition = {
  version: 22,
  name: 'turn_progress_text_compat',
  apply(database: Database) {
    if (!tableHasColumn(database, 'paired_turns', 'progress_text')) {
      database.exec(`ALTER TABLE paired_turns ADD COLUMN progress_text TEXT`);
    }
    if (!tableHasColumn(database, 'paired_turns', 'progress_updated_at')) {
      database.exec(
        `ALTER TABLE paired_turns ADD COLUMN progress_updated_at TEXT`,
      );
    }
  },
};
