'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [countries, states, cities] = await Promise.all([
      queryInterface.sequelize.query("SELECT id FROM country WHERE country_code = 'IND' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id FROM state WHERE state_code = 'MH' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id FROM city WHERE city_code = 'MUM' LIMIT 1")
    ]);

    const countryId = countries[0].length > 0 ? countries[0][0].id : null;
    const stateId = states[0].length > 0 ? states[0][0].id : null;
    const cityId = cities[0].length > 0 ? cities[0][0].id : null;

    const banks = [
      { bank_code: 'SBI', bank_name: 'State Bank of India', bank_short_name: 'SBI', ifsc_code: 'SBIN', bank_type: 'PUBLIC_SECTOR' },
      { bank_code: 'HDFC', bank_name: 'HDFC Bank Limited', bank_short_name: 'HDFC', ifsc_code: 'HDFC', bank_type: 'PRIVATE_SECTOR' },
      { bank_code: 'ICICI', bank_name: 'ICICI Bank Limited', bank_short_name: 'ICICI', ifsc_code: 'ICIC', bank_type: 'PRIVATE_SECTOR' },
      { bank_code: 'AXIS', bank_name: 'Axis Bank Limited', bank_short_name: 'AXIS', ifsc_code: 'UTIB', bank_type: 'PRIVATE_SECTOR' },
      { bank_code: 'PNB', bank_name: 'Punjab National Bank', bank_short_name: 'PNB', ifsc_code: 'PUNB', bank_type: 'PUBLIC_SECTOR' }
    ];
    const dialect = queryInterface.sequelize.getDialect ? queryInterface.sequelize.getDialect() : 'mysql';
    if (dialect === 'mysql' || dialect === 'mariadb') {
      for (const r of banks) {
        await queryInterface.sequelize.query(
          `INSERT IGNORE INTO bank (bank_code, bank_name, bank_short_name, ifsc_code, bank_type, city_id, state_id, country_id, status, created_at, updated_at)
           VALUES (:bank_code, :bank_name, :bank_short_name, :ifsc_code, :bank_type, :city_id, :state_id, :country_id, 'ACTIVE', NOW(), NOW())`,
          { replacements: { ...r, city_id: cityId, state_id: stateId, country_id: countryId } }
        );
      }
    } else {
      await queryInterface.bulkInsert('bank', banks.map((r) => ({
        ...r,
        city_id: cityId,
        state_id: stateId,
        country_id: countryId,
        status: 'ACTIVE',
        created_at: new Date(),
        updated_at: new Date()
      })), { ignoreDuplicates: true });
    }
  },

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

