'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [companies, uoms, users] = await Promise.all([
      queryInterface.sequelize.query("SELECT id FROM company WHERE code = 'COMP001' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id, uom_code FROM uom WHERE uom_code IN ('PC', 'KG', 'LTR')"),
      queryInterface.sequelize.query("SELECT id FROM user WHERE username = 'admin' LIMIT 1")
    ]);

    if (companies[0].length === 0 || users[0].length === 0) return;

    const companyId = companies[0][0].id;
    const userId = users[0][0].id;

    const uomMap = {};
    uoms[0].forEach(uom => {
      uomMap[uom.uom_code] = uom.id;
    });

    await queryInterface.bulkInsert('material', [
      {
        company_id: companyId,
        material_number: 'MAT001',
        material_type: 'RAW_MATERIAL',
        material_group: 'RAW',
        description: 'Steel Sheets',
        base_uom_id: uomMap['KG'],
        hsn_code: '72101200',
        is_batch_managed: false,
        is_serial_managed: false,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        company_id: companyId,
        material_number: 'MAT002',
        material_type: 'RAW_MATERIAL',
        material_group: 'RAW',
        description: 'Aluminum Ingots',
        base_uom_id: uomMap['KG'],
        hsn_code: '76011000',
        is_batch_managed: false,
        is_serial_managed: false,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        company_id: companyId,
        material_number: 'MAT003',
        material_type: 'FINISHED_GOOD',
        material_group: 'FG',
        description: 'Finished Product A',
        base_uom_id: uomMap['PC'],
        hsn_code: '73089000',
        is_batch_managed: false,
        is_serial_managed: false,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        company_id: companyId,
        material_number: 'MAT004',
        material_type: 'PACKAGING',
        material_group: 'PKG',
        description: 'Cardboard Box',
        base_uom_id: uomMap['PC'],
        hsn_code: '48191000',
        is_batch_managed: false,
        is_serial_managed: false,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      }
    ]);
  },

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

