'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('vendor_category', {
      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: 'RESTRICT'
      },
      category_code: {
        type: Sequelize.STRING(20),
        allowNull: false,
        comment: 'Unique code for vendor category (e.g., REGULAR, SUB_CONTRACTOR, JOB_WORKER)'
      },
      category_name: {
        type: Sequelize.STRING(100),
        allowNull: false,
        comment: 'Name of vendor category (e.g., Regular Vendor, Sub Contractor, Job Worker)'
      },
      description: {
        type: Sequelize.STRING(500),
        allowNull: true
      },
      gst_reduction_percentage: {
        type: Sequelize.DECIMAL(5, 2),
        allowNull: true,
        defaultValue: 0.00,
        comment: 'GST reduction percentage for this category (e.g., 6% reduction means 18% becomes 12%)'
      },
      applies_to_raw_materials: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: true,
        comment: 'Whether GST reduction applies to raw materials'
      },
      applies_to_semi_finished: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: true,
        comment: 'Whether GST reduction applies to semi-finished materials'
      },
      is_active: {
        type: Sequelize.BOOLEAN,
        allowNull: false,
        defaultValue: true
      },
      created_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'user',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      },
      updated_by: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'user',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'SET NULL'
      },
      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')
      }
    });

    // Add unique index
    await queryInterface.addIndex('vendor_category', {
      fields: ['company_id', 'category_code'],
      unique: true,
      name: 'vendor_category_company_code_unique'
    });
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('vendor_category');
  }
};

