'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    // Get all companies
    const [companies] = await queryInterface.sequelize.query(
      "SELECT id FROM company"
    );

    // Get admin user for created_by
    const [users] = await queryInterface.sequelize.query(
      "SELECT id FROM user WHERE username = 'admin' LIMIT 1"
    );

    const userId = users.length > 0 ? users[0].id : null;

    // Insert ASSEMBLY material type for each company if it doesn't exist
    for (const company of companies) {
      const companyId = company.id;
      
      // Check if ASSEMBLY already exists for this company
      const [existing] = await queryInterface.sequelize.query(
        `SELECT id FROM material_type WHERE company_id = :companyId AND type_code = 'ASSEMBLY' LIMIT 1`,
        {
          replacements: { companyId },
          type: Sequelize.QueryTypes.SELECT
        }
      );

      if (!existing || existing.length === 0) {
        await queryInterface.bulkInsert('material_type', [{
          company_id: companyId,
          type_code: 'ASSEMBLY',
          type_name: 'Assembly',
          description: 'Assembled components or sub-assemblies',
          is_active: true,
          created_by: userId,
          created_at: new Date(),
          updated_at: new Date()
        }]);
      }
    }
  },

  async down(queryInterface, Sequelize) {
    // Remove ASSEMBLY material types
    await queryInterface.sequelize.query(
      "DELETE FROM material_type WHERE type_code = 'ASSEMBLY'"
    );
  }
};

