import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Store the exchange rate exactly as the accounts user entered it, in
 * their natural quote direction ("1 Bill = X Receive", e.g.
 * 1 AED = 26.37 INR), for faithful future reference on receipts and
 * history.
 *
 * `exchange_rate` remains the canonical bill-per-receive figure used by
 * the conversion maths (`bill = receive × exchange_rate`). This new
 * column is the human-entered quote — the reciprocal — kept verbatim so
 * a reopened receipt shows `26.37`, not `0.037922` (nor `26.3699` from
 * inverting the rounded canonical rate). Nullable: pre-existing rows and
 * same-currency collections leave it empty.
 *
 * Wider precision than `exchange_rate` (18,6 vs 12,6) because a natural
 * quote can be large (e.g. 1 USD = 15000 IDR).
 */
export class CollectExchangeRateQuote1787700000000 implements MigrationInterface {
  name = 'CollectExchangeRateQuote1787700000000';

  public async up(qr: QueryRunner): Promise<void> {
    for (const table of ['payment_collections', 'booking_cash_collection_batches']) {
      await qr.query(
        `ALTER TABLE "${table}" ADD COLUMN IF NOT EXISTS "exchange_rate_quote" numeric(18,6) NULL`,
      );
      await qr.query(`
        ALTER TABLE "${table}"
          ADD CONSTRAINT "chk_${table}_exchange_rate_quote_non_neg"
            CHECK ("exchange_rate_quote" IS NULL OR "exchange_rate_quote" >= 0)
      `);
    }
  }

  public async down(qr: QueryRunner): Promise<void> {
    for (const table of ['payment_collections', 'booking_cash_collection_batches']) {
      await qr.query(
        `ALTER TABLE "${table}" DROP CONSTRAINT IF EXISTS "chk_${table}_exchange_rate_quote_non_neg"`,
      );
      await qr.query(`ALTER TABLE "${table}" DROP COLUMN IF EXISTS "exchange_rate_quote"`);
    }
  }
}
