import { MigrationInterface, QueryRunner } from 'typeorm';

import { CONTRACT_TEMPLATE_DEFAULTS } from '../seed/data/contract-template-defaults';

/**
 * Refresh the `pricing` article body of the six seeded contract templates to
 * the live-rate-schedule wording. The per-lane figures (e.g. "USD 400 per
 * wagon") are now rendered from the LIVE rate config instead of frozen prose,
 * so any template whose pricing article still carries a hardcoded price token
 * is rewritten to the current seed text.
 *
 * The guard `body ~ '(USD|ETB) [0-9]'` identifies the auto-seeded original
 * prose (which always quoted a currency + figure) and matches neither an
 * already-migrated body nor a hand-edited one that adopted the schedule
 * wording — so admin edits are preserved. Idempotent: after the rewrite the
 * price token is gone, so a re-run is a no-op. Fresh databases seed the new
 * text directly (CreateContractTemplates imports the same seed), making this
 * a targeted backfill for databases seeded before the seed changed.
 */
const HARDCODED_PRICE_TOKEN = '(USD|ETB) [0-9]';

export class RefreshContractPricingArticles2360000000000
  implements MigrationInterface
{
  public async up(queryRunner: QueryRunner): Promise<void> {
    for (const seed of CONTRACT_TEMPLATE_DEFAULTS) {
      const pricing = seed.articles.find((a) => a.id === 'pricing');
      if (!pricing) continue;

      // Rewrite only the article whose id = 'pricing', in place, and only when
      // its body still quotes a hardcoded currency figure. jsonb_agg keeps the
      // rest of the article (id/title/order) and every other article intact.
      await queryRunner.query(
        `
        UPDATE freight.contract_templates AS t
        SET articles = (
          SELECT jsonb_agg(
            CASE
              WHEN elem->>'id' = 'pricing'
                THEN jsonb_set(elem, '{body}', to_jsonb($2::text), true)
              ELSE elem
            END
            ORDER BY ord
          )
          FROM jsonb_array_elements(t.articles) WITH ORDINALITY AS a(elem, ord)
        ),
        updated_at = now()
        WHERE t.code = $1
          AND EXISTS (
            SELECT 1
            FROM jsonb_array_elements(t.articles) AS x
            WHERE x->>'id' = 'pricing'
              AND x->>'body' ~ $3
          );
        `,
        [seed.code, pricing.body, HARDCODED_PRICE_TOKEN],
      );
    }
  }

  /**
   * Irreversible in practice — the original per-lane figures are not restored.
   * A no-op down keeps the migration reversible-by-contract without
   * resurrecting stale hardcoded prices.
   */
  public async down(): Promise<void> {
    // intentionally empty
  }
}
