import { QueryInterface, DataTypes } from 'sequelize';

module.exports = {
  up: async (queryInterface: QueryInterface) => {
    // 1. Add sessionToken to users table
    await queryInterface.addColumn('users', 'sessionToken', {
      type: DataTypes.UUID,
      allowNull: true,
      comment: 'Unique token for active session to restrict concurrent logins'
    });

    // 2. Add lastLoginDevice to users table
    await queryInterface.addColumn('users', 'lastLoginDevice', {
      type: DataTypes.STRING(255),
      allowNull: true,
      comment: 'Browser/Device string from User-Agent of the active session'
    });

    // 3. Create hsn_sac_codes table
    await queryInterface.createTable('hsn_sac_codes', {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      code: {
        type: DataTypes.STRING(100),
        allowNull: false,
        comment: 'The HSN or SAC code value'
      },
      type: {
        type: DataTypes.ENUM('HSN', 'SAC'),
        allowNull: false,
        comment: 'Type of code: either HSN or SAC'
      },
      gstRate: {
        type: DataTypes.DECIMAL(5, 2),
        allowNull: true,
        field: 'gst_rate',
        comment: 'Associated GST rate percentage'
      },
      description: {
        type: DataTypes.TEXT,
        allowNull: true,
        comment: 'Description of the code'
      },
      isActive: {
        type: DataTypes.BOOLEAN,
        defaultValue: true,
        allowNull: false,
        field: 'is_active'
      },
      createdAt: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
        field: 'created_at'
      },
      updatedAt: {
        type: DataTypes.DATE,
        allowNull: false,
        defaultValue: DataTypes.NOW,
        field: 'updated_at'
      }
    });

    // Add indexes to hsn_sac_codes
    await queryInterface.addIndex('hsn_sac_codes', ['code']);
    await queryInterface.addIndex('hsn_sac_codes', ['type']);
    await queryInterface.addIndex('hsn_sac_codes', ['is_active']);
  },

  down: async (queryInterface: QueryInterface) => {
    // Drop hsn_sac_codes table
    await queryInterface.dropTable('hsn_sac_codes');

    // Remove columns from users table
    await queryInterface.removeColumn('users', 'lastLoginDevice');
    await queryInterface.removeColumn('users', 'sessionToken');

    // Also drop the ENUM type created for hsn_sac_codes type
    await queryInterface.sequelize.query('DROP TYPE IF EXISTS "enum_hsn_sac_codes_type";');
  }
};
