'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [currencies, cities, states, countries] = await Promise.all([
      queryInterface.sequelize.query("SELECT id FROM currency WHERE currency_code = 'INR' 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")
    ]);

    const currencyId = currencies[0].length > 0 ? currencies[0][0].id : null;
    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 = {
      code: 'COMP001',
      name: 'ABC Manufacturing Private Limited',
      legal_name: 'ABC Manufacturing Private Limited',
      pan: 'AAAAA0000A',
      cin: 'U12345MH2020PTC123456',
      registration_number: '123456',
      registration_date: '2020-01-01',
      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: 'info@abcmanufacturing.com',
      website: 'www.abcmanufacturing.com',
      currency_id: currencyId,
      financial_year_start: '04-01',
      status: 'ACTIVE'
    };
    if (dialect === 'mysql' || dialect === 'mariadb') {
      await queryInterface.sequelize.query(
        `INSERT IGNORE INTO company (code, name, legal_name, pan, cin, registration_number, registration_date, address_line1, address_line2, city_id, state_id, country_id, pincode, phone, email, website, currency_id, financial_year_start, status, created_at, updated_at)
         VALUES (:code, :name, :legal_name, :pan, :cin, :registration_number, :registration_date, :address_line1, :address_line2, :city_id, :state_id, :country_id, :pincode, :phone, :email, :website, :currency_id, :financial_year_start, :status, NOW(), NOW())`,
        { replacements: row }
      );
    } else {
      await queryInterface.bulkInsert('company', [{ ...row, created_at: new Date(), updated_at: new Date() }], { ignoreDuplicates: true });
    }
  },

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

