'use strict';

// This migration aligns the GRDs table schema with the application code.
// It ensures the column is named `codigo` (VARCHAR(50) UNIQUE),
// renaming legacy `numero_grd` if present.

module.exports = {
  async up(queryInterface, Sequelize) {
    // Check for legacy column
    const [legacy] = await queryInterface.sequelize.query("SHOW COLUMNS FROM grds LIKE 'numero_grd'");
    if (Array.isArray(legacy) && legacy.length > 0) {
      // Rename numero_grd -> codigo and set type to VARCHAR(50)
      await queryInterface.sequelize.query(
        "ALTER TABLE grds CHANGE COLUMN numero_grd codigo VARCHAR(50) NOT NULL"
      );
      // Ensure unique index on codigo
      const [idx] = await queryInterface.sequelize.query("SHOW INDEX FROM grds WHERE Key_name = 'codigo_unique'");
      if (!Array.isArray(idx) || idx.length === 0) {
        await queryInterface.sequelize.query("ALTER TABLE grds ADD UNIQUE KEY codigo_unique (codigo)");
      }
    } else {
      // Ensure `codigo` exists
      const [codigo] = await queryInterface.sequelize.query("SHOW COLUMNS FROM grds LIKE 'codigo'");
      if (!Array.isArray(codigo) || codigo.length === 0) {
        await queryInterface.sequelize.query(
          "ALTER TABLE grds ADD COLUMN codigo VARCHAR(50) NOT NULL UNIQUE"
        );
      }
    }
  },
  async down(queryInterface, Sequelize) {
    // Attempt to revert: rename codigo back to numero_grd (INT)
    const [codigo] = await queryInterface.sequelize.query("SHOW COLUMNS FROM grds LIKE 'codigo'");
    if (Array.isArray(codigo) && codigo.length > 0) {
      // Drop explicit unique index if exists
      const [idx] = await queryInterface.sequelize.query("SHOW INDEX FROM grds WHERE Key_name = 'codigo_unique'");
      if (Array.isArray(idx) && idx.length > 0) {
        await queryInterface.sequelize.query("ALTER TABLE grds DROP INDEX codigo_unique");
      }
      await queryInterface.sequelize.query(
        "ALTER TABLE grds CHANGE COLUMN codigo numero_grd INT NOT NULL"
      );
    }
  }
};