import { MigrationInterface, QueryRunner, TableColumn } from 'typeorm';

/**
 * Proof of Delivery (customer pickup) capture on cargoes:
 * receiver name, delivered/picked-up timestamp, and delivery remarks.
 */
export class AddProofOfDeliveryToCargoes1750000000002 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable('freight.cargoes');
    if (!table) {
      // cargoes table doesn't exist yet, skip this migration
      return;
    }

    const columnsToAdd = [
      { name: 'receiver_name', type: 'varchar', isNullable: true },
      { name: 'delivered_at', type: 'timestamp', isNullable: true },
      { name: 'delivery_remarks', type: 'text', isNullable: true },
    ];

    const columnsToCreate = columnsToAdd.filter(
      (col) => !table.columns.some((c) => c.name === col.name),
    );

    if (columnsToCreate.length > 0) {
      await queryRunner.addColumns(
        'freight.cargoes',
        columnsToCreate.map((col) => new TableColumn(col)),
      );
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const table = await queryRunner.getTable('freight.cargoes');
    if (!table) {
      return;
    }

    const columnNames = ['receiver_name', 'delivered_at', 'delivery_remarks'];
    const columnsToRemove = columnNames.filter((name) =>
      table.columns.some((c) => c.name === name),
    );

    if (columnsToRemove.length > 0) {
      await queryRunner.dropColumns('freight.cargoes', columnsToRemove);
    }
  }
}
