'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('number_sequence', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      company_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'company', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
        comment: 'Company for this sequence'
      },
      module_name: {
        type: Sequelize.STRING(50),
        allowNull: false,
        comment: 'Module: PRODUCTION_ORDER, MATERIAL_REQUEST, PURCHASE_ORDER, etc.'
      },
      fiscal_year_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: { model: 'fiscal_year', key: 'id' },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
        comment: 'Sequence resets per fiscal year'
      },
      current_sequence: {
        type: Sequelize.INTEGER,
        allowNull: false,
        defaultValue: 0,
        comment: 'Last used sequence number for this company+module+FY'
      },
      created_at: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      },
      updated_at: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')
      }
    });

    await queryInterface.addIndex('number_sequence', ['company_id', 'module_name', 'fiscal_year_id'], {
      unique: true,
      name: 'unique_company_module_fiscal_year'
    });
    await queryInterface.addIndex('number_sequence', ['company_id', 'module_name'], {
      name: 'idx_number_sequence_company_module'
    });
  },

  async down(queryInterface) {
    await queryInterface.dropTable('number_sequence');
  }
};
