'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const table = 'operation_name';
    const cols = await queryInterface.describeTable(table);

    // If operation_no already exists, nothing to do.
    if (cols.operation_no) return;

    // If an earlier migration created operation_name (string), rename it to operation_no (int).
    // MySQL allows renameColumn, but does not automatically convert types; we'll do a safe approach:
    // - add operation_no (int)
    // - backfill from operation_name where possible
    // - keep operation_name (optional) OR drop it
    // We'll drop the old column at the end to avoid Sequelize "unknown column" issues.

    await queryInterface.addColumn(table, 'operation_no', {
      type: Sequelize.INTEGER,
      allowNull: true,
      after: 'operation_code',
    });

    if (cols.operation_name) {
      // Copy numeric values only; non-numeric becomes NULL.
      // eslint-disable-next-line no-useless-escape
      await queryInterface.sequelize.query(
        `UPDATE \`${table}\` SET operation_no = CAST(operation_name AS SIGNED) WHERE operation_name REGEXP '^[0-9]+$'`
      );

      await queryInterface.removeColumn(table, 'operation_name');
    }
  },

  async down(queryInterface, Sequelize) {
    const table = 'operation_name';
    const cols = await queryInterface.describeTable(table);

    if (cols.operation_no && !cols.operation_name) {
      await queryInterface.addColumn(table, 'operation_name', {
        type: Sequelize.STRING(200),
        allowNull: true,
        after: 'operation_code',
      });

      await queryInterface.sequelize.query(
        `UPDATE \`${table}\` SET operation_name = CAST(operation_no AS CHAR) WHERE operation_no IS NOT NULL`
      );

      await queryInterface.removeColumn(table, 'operation_no');
    } else if (cols.operation_no) {
      await queryInterface.removeColumn(table, 'operation_no');
    }
  },
};

