import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Adds:
 *   1. leads.client_group  — ENUM('QRS','TQS','QRS_B','QRS_NEW') NULL
 *   2. leads.assigned_by   — who performed the last reassignment
 *   3. leads.assigned_at   — when it happened
 *
 * client_group is NULLABLE on purpose: existing rows stay valid and the
 * form can require it going forward without a data backfill. If you want
 * every legacy row to land in a group, uncomment the backfill block below
 * and set the default you want.
 *
 * QRS_B is included in the ENUM even though the dropdown never offers it,
 * because legacy rows may already hold that value. The application layer
 * (CLIENT_GROUP_ROLLUP in lead.entity.ts) folds QRS_B into QRS for every
 * filter, group-by and report.
 */
export class AddClientGroupAndAssignmentToLeads1753900000000
  implements MigrationInterface
{
  name = 'AddClientGroupAndAssignmentToLeads1753900000000';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      ALTER TABLE \`leads\`
        ADD COLUMN \`client_group\` ENUM('QRS','TQS','QRS_B','QRS_NEW') NULL
          AFTER \`company\`
    `);

    await queryRunner.query(`
      ALTER TABLE \`leads\`
        ADD INDEX \`IDX_leads_client_group\` (\`client_group\`)
    `);

    await queryRunner.query(`
      ALTER TABLE \`leads\`
        ADD COLUMN \`assigned_by\` INT NULL AFTER \`assigned_to\`,
        ADD COLUMN \`assigned_at\` TIMESTAMP NULL AFTER \`assigned_by\`
    `);

    await queryRunner.query(`
      ALTER TABLE \`leads\`
        ADD CONSTRAINT \`FK_leads_assigned_by\`
          FOREIGN KEY (\`assigned_by\`) REFERENCES \`users\`(\`id\`)
          ON DELETE SET NULL ON UPDATE CASCADE
    `);

    // ── Optional backfill ────────────────────────────────────────────────
    // Every lead created before this migration gets QRS. Uncomment if you
    // want that; leave commented to keep them NULL / "Unassigned group".
    //
    // await queryRunner.query(
    //   `UPDATE \`leads\` SET \`client_group\` = 'QRS' WHERE \`client_group\` IS NULL`,
    // );
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(
      `ALTER TABLE \`leads\` DROP FOREIGN KEY \`FK_leads_assigned_by\``,
    );
    await queryRunner.query(
      `ALTER TABLE \`leads\` DROP COLUMN \`assigned_at\`, DROP COLUMN \`assigned_by\``,
    );
    await queryRunner.query(
      `ALTER TABLE \`leads\` DROP INDEX \`IDX_leads_client_group\``,
    );
    await queryRunner.query(
      `ALTER TABLE \`leads\` DROP COLUMN \`client_group\``,
    );
  }
}
