import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Phase D §12d Gap #2 — credit DEBIT path.
 *
 * Adds `credit_applied` to payment_collections so a single Collection
 * Screen submission can record both the cash received AND any credit
 * drawn down from the party's customer_credit_ledger. Allocation cap
 * becomes `received_amount + credit_applied`; the ledger DEBIT is
 * written in the same transaction as the collection row.
 *
 * Default 0 keeps every legacy row backwards-compatible without any
 * backfill.
 */
export class PaymentCollectionsCreditApplied1782200000000 implements MigrationInterface {
  name = 'PaymentCollectionsCreditApplied1782200000000';

  public async up(qr: QueryRunner): Promise<void> {
    await qr.query(`
      ALTER TABLE payment_collections
        ADD COLUMN credit_applied numeric(12,2) NOT NULL DEFAULT 0;
    `);
    await qr.query(`
      ALTER TABLE payment_collections
        ADD CONSTRAINT payment_collections_credit_applied_nonneg
          CHECK (credit_applied >= 0);
    `);
  }

  public async down(qr: QueryRunner): Promise<void> {
    await qr.query(`
      ALTER TABLE payment_collections
        DROP CONSTRAINT IF EXISTS payment_collections_credit_applied_nonneg;
    `);
    await qr.query(`
      ALTER TABLE payment_collections
        DROP COLUMN IF EXISTS credit_applied;
    `);
  }
}
