import { MigrationInterface, QueryRunner } from 'typeorm';

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

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

    await queryRunner.query(`
      ALTER TABLE freight.external_profiles
        ADD COLUMN IF NOT EXISTS onboarding_step varchar(40);
    `);

    await queryRunner.query(`
      ALTER TABLE freight.external_profiles
        ADD COLUMN IF NOT EXISTS onboarding_completed boolean NOT NULL DEFAULT false;
    `);

    // Existing users already use the portal — never re-gate them behind the
    // new onboarding wizard.
    await queryRunner.query(`
      UPDATE freight.external_profiles
        SET onboarding_completed = true
        WHERE onboarding_completed = false;
    `);

    // Backfill the active mode for existing users from their company's
    // operational profiles. Prefer importer, then exporter, then whichever
    // single profile the company has (forwarder/dj/transporter).
    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;
    `);
  }

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