import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Drop the `active_profile_type` "active mode" column. A booking/contract now
 * resolves its company_profile from the trade direction at creation time (with
 * a forwarder passing an explicit companyProfileId), so no per-user active mode
 * is stored. `onboarding_step` / `onboarding_completed` are unaffected.
 */
export class DropActiveProfileTypeFromExternalProfiles2450000000000
  implements MigrationInterface
{
  name = 'DropActiveProfileTypeFromExternalProfiles2450000000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.external_profiles
        DROP COLUMN IF EXISTS active_profile_type;
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE freight.external_profiles
        ADD COLUMN IF NOT EXISTS active_profile_type varchar(32);
    `);
    // Rebuild the mode the same way the original column was backfilled:
    // importer first, then exporter, then whichever profile the company has.
    await queryRunner.query(`
      UPDATE freight.external_profiles ep
        SET active_profile_type = cp.type
        FROM (
          SELECT DISTINCT ON (company_id) company_id, type
            FROM freight.company_profiles
            ORDER BY company_id,
              CASE type
                WHEN 'importer' THEN 0
                WHEN 'exporter' THEN 1
                ELSE 2
              END
        ) cp
        WHERE ep.company_id = cp.company_id
          AND ep.active_profile_type IS NULL;
    `);
  }
}
