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

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

/**
 * Recovery for a migration-version collision introduced by merging
 * origin/main into the long-lived deployment branch.
 *
 * The deployment DB recorded schema version 15 as `reviewer_failure_count`
 * (a downstream-only migration), while upstream defines version 15 as
 * `turn_progress_text` (migration 015). Because the migration runner tracks
 * applied migrations by version number alone, the upstream `turn_progress_text`
 * migration is skipped on the live DB and `paired_turns.progress_text` /
 * `progress_updated_at` are never created — even though merged runtime code
 * (src/db/paired-turns.ts, src/web-dashboard-data.ts) reads and writes them.
 *
 * This migration re-applies those columns idempotently under a fresh version
 * number so the live deployment gets them. It is a no-op on databases where
 * migration 015 already ran (fresh installs), thanks to the column guards.
 */
export const TURN_PROGRESS_TEXT_RECOVERY_MIGRATION: SchemaMigrationDefinition =
  {
    version: 19,
    name: 'turn_progress_text_recovery',
    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`,
        );
      }
    },
  };
