import { MigrationInterface, QueryRunner } from 'typeorm';

export class MoveBusinessLicenseToProfile1752000000001
  implements MigrationInterface
{
  name = 'MoveBusinessLicenseToProfile1752000000001';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      UPDATE freight.company_profiles cp
      SET business_license = c.business_license
      FROM freight.companies c
      WHERE cp.company_id = c.id AND c.business_license IS NOT NULL
    `);

    await queryRunner.query(
      `ALTER TABLE freight.companies DROP COLUMN IF EXISTS business_license`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `ALTER TABLE freight.companies ADD COLUMN business_license varchar(100) NULL`,
    );

    await queryRunner.query(`
      UPDATE freight.companies c
      SET business_license = cp.business_license
      FROM (
        SELECT DISTINCT ON (cp2.company_id)
          cp2.company_id, cp2.business_license
        FROM freight.company_profiles cp2
        WHERE cp2.business_license IS NOT NULL
        ORDER BY cp2.company_id, cp2.created_at
      ) cp
      WHERE cp.company_id = c.id
    `);
  }
}
