import { MigrationInterface, QueryRunner } from "typeorm";

/**
 * Company-profile references are now minted only when a profile is approved
 * (status → Active); pending profiles carry NULL. Drop the NOT NULL constraint
 * on freight.company_profiles.reference. The existing unique index is kept —
 * Postgres treats NULLs as distinct, so multiple pending (NULL) profiles don't
 * collide.
 */
export class MakeCompanyProfileReferenceNullable1810000000002
  implements MigrationInterface
{
  name = "MakeCompanyProfileReferenceNullable1810000000002";

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `ALTER TABLE "freight"."company_profiles" ALTER COLUMN "reference" DROP NOT NULL`,
    );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Reinstating NOT NULL requires every row to have a reference; any pending
    // (NULL) profiles get a placeholder so the constraint can be re-applied.
    await queryRunner.query(
      `UPDATE "freight"."company_profiles" SET "reference" = 'PENDING-' || left(replace("id"::text, '-', ''), 12) WHERE "reference" IS NULL`,
    );
    await queryRunner.query(
      `ALTER TABLE "freight"."company_profiles" ALTER COLUMN "reference" SET NOT NULL`,
    );
  }
}
