'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [companies, cities, states, countries, users] = await Promise.all([
      queryInterface.sequelize.query("SELECT id FROM company WHERE code = 'COMP001' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id FROM city WHERE city_code = 'MUM' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id FROM state WHERE state_code = 'MH' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id FROM country WHERE country_code = 'IND' LIMIT 1"),
      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 cityId = cities[0].length > 0 ? cities[0][0].id : null;
    const stateId = states[0].length > 0 ? states[0][0].id : null;
    const countryId = countries[0].length > 0 ? countries[0][0].id : null;

    const dialect = queryInterface.sequelize.getDialect ? queryInterface.sequelize.getDialect() : 'mysql';
    const row = {
      company_id: companyId,
      code: 'PLANT001',
      name: 'Main Manufacturing Plant',
      plant_type: 'MANUFACTURING',
      address_line1: '123 Industrial Area',
      address_line2: 'MIDC, Phase 1',
      city_id: cityId,
      state_id: stateId,
      country_id: countryId,
      pincode: '400001',
      phone: '022-12345678',
      email: 'plant@abcmanufacturing.com',
      status: 'ACTIVE',
      created_by: userId
    };
    if (dialect === 'mysql' || dialect === 'mariadb') {
      await queryInterface.sequelize.query(
        `INSERT IGNORE INTO plant (company_id, code, name, plant_type, address_line1, address_line2, city_id, state_id, country_id, pincode, phone, email, status, created_by, created_at, updated_at)
         VALUES (:company_id, :code, :name, :plant_type, :address_line1, :address_line2, :city_id, :state_id, :country_id, :pincode, :phone, :email, :status, :created_by, NOW(), NOW())`,
        { replacements: row }
      );
    } else {
      await queryInterface.bulkInsert('plant', [{ ...row, created_at: new Date(), updated_at: new Date() }], { ignoreDuplicates: true });
    }
  },

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

