'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [companies] = await queryInterface.sequelize.query(
      "SELECT id FROM company"
    );
    const [users] = await queryInterface.sequelize.query(
      "SELECT id FROM user WHERE username = 'admin' LIMIT 1"
    );
    const userId = users.length > 0 ? users[0].id : null;
    
    const materialGroups = [
      { group_code: 'CABINET', group_name: 'Cabinet', description: 'Cabinet assemblies and finished goods', is_active: true },
      { group_code: 'ASSEMBLY', group_name: 'Assembly', description: 'Sub-assemblies and intermediate components', is_active: true },
      { group_code: 'PARTS', group_name: 'Parts', description: 'Individual parts and components', is_active: true },
      { group_code: 'FASTENERS', group_name: 'Fasteners', description: 'Screws, bolts, nuts, and other fastening components', is_active: true },
      { group_code: 'ELECTRICAL', group_name: 'Electrical', description: 'Electrical components and wiring', is_active: true },
      { group_code: 'MECHANICAL', group_name: 'Mechanical', description: 'Mechanical components and hardware', is_active: true },
      { group_code: 'RAW_MAT', group_name: 'Raw Material', description: 'Raw materials for production', is_active: true },
      { group_code: 'PACKAGING', group_name: 'Packaging', description: 'Packaging materials and supplies', is_active: true },
      { group_code: 'CONSUMABLE', group_name: 'Consumable', description: 'Consumable items used in production', is_active: true },
      { group_code: 'TOOLING', group_name: 'Tooling', description: 'Tools and tooling equipment', is_active: true },
    ];

    for (const company of companies) {
      const companyId = company.id;
      for (const materialGroup of materialGroups) {
        const [existing] = await queryInterface.sequelize.query(
          `SELECT id FROM material_group WHERE company_id = :companyId AND group_code = :groupCode LIMIT 1`,
          { replacements: { companyId, groupCode: materialGroup.group_code }, type: Sequelize.QueryTypes.SELECT }
        );
        if (!existing || existing.length === 0) {
          await queryInterface.bulkInsert('material_group', [{
            company_id: companyId,
            group_code: materialGroup.group_code,
            group_name: materialGroup.group_name,
            description: materialGroup.description,
            is_active: materialGroup.is_active,
            created_by: userId,
            created_at: new Date(),
            updated_at: new Date()
          }]);
        }
      }
    }
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.bulkDelete('material_group', null, {});
  }
};

