import { MigrationInterface, QueryRunner } from 'typeorm';

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

/**
 * Refresh the "pricing" article of each seeded contract template so it points
 * at the live Rate Schedule instead of hardcoded price figures (USD 400/wagon,
 * USD 919/40ft, …). The original CreateContractTemplates migration seeded the
 * old prose with ON CONFLICT DO NOTHING, so those figures are frozen in the DB
 * rows and would otherwise contradict the rate-config-driven schedule table now
 * rendered under the pricing article.
 *
 * Only the article whose id = 'pricing' is touched, and only when its body
 * still matches the originally-seeded prose — so any admin edit to the pricing
 * article is left untouched. Idempotent: re-running is a no-op once refreshed.
 */
export class RefreshContractPricingArticles2350000000000
  implements MigrationInterface
{
  public async up(queryRunner: QueryRunner): Promise<void> {
    for (const seed of CONTRACT_TEMPLATE_DEFAULTS) {
      const pricing = seed.articles.find((article) => article.id === 'pricing');
      if (!pricing) continue;

      // jsonb_set the title + body of the element whose id = 'pricing', matched
      // by array index. Guarded so admin-edited bodies are never overwritten.
      await queryRunner.query(
        `
        UPDATE freight.contract_templates ct
        SET articles = (
          SELECT jsonb_agg(
            CASE
              WHEN elem->>'id' = 'pricing'
              THEN elem || jsonb_build_object('title', $2::text, 'body', $3::text)
              ELSE elem
            END
          )
          FROM jsonb_array_elements(ct.articles) elem
        )
        WHERE ct.code = $1
          AND EXISTS (
            SELECT 1 FROM jsonb_array_elements(ct.articles) e
            WHERE e->>'id' = 'pricing'
              AND e->>'body' LIKE ANY (ARRAY[
                '%USD 59.4 per metric ton%',
                '%USD 696 (six hundred ninety-six) per wagon%',
                '%USD 400 (four hundred) per wagon%',
                '%From SGTD to Dire Dawa dry port, the rate is USD 919%',
                '%Railway transportation charges from GMP to SGTD: USD 819%',
                '%prevailing EDR domestic container tariff, as set out in the commercial schedule%'
              ])
          );
        `,
        [seed.code, pricing.title, pricing.body],
      );
    }
  }

  public async down(): Promise<void> {
    // No-op: the refreshed pricing prose is the correct forward state; reverting
    // to hardcoded figures would reintroduce the rate-schedule contradiction.
  }
}
