'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [countries] = await queryInterface.sequelize.query(
      "SELECT id FROM country WHERE country_code = 'IND' LIMIT 1"
    );
    if (countries.length === 0) return;
    const indiaId = countries[0].id;

    const states = [
      { state_code: 'MH', state_name: 'Maharashtra', gst_state_code: '27', is_union_territory: 0, is_active: 1 },
      { state_code: 'DL', state_name: 'Delhi', gst_state_code: '07', is_union_territory: 1, is_active: 1 },
      { state_code: 'KA', state_name: 'Karnataka', gst_state_code: '29', is_union_territory: 0, is_active: 1 },
      { state_code: 'TN', state_name: 'Tamil Nadu', gst_state_code: '33', is_union_territory: 0, is_active: 1 },
      { state_code: 'GJ', state_name: 'Gujarat', gst_state_code: '24', is_union_territory: 0, is_active: 1 },
      { state_code: 'RJ', state_name: 'Rajasthan', gst_state_code: '08', is_union_territory: 0, is_active: 1 },
      { state_code: 'UP', state_name: 'Uttar Pradesh', gst_state_code: '09', is_union_territory: 0, is_active: 1 },
      { state_code: 'WB', state_name: 'West Bengal', gst_state_code: '19', is_union_territory: 0, is_active: 1 },
      { state_code: 'AP', state_name: 'Andhra Pradesh', gst_state_code: '37', is_union_territory: 0, is_active: 1 },
      { state_code: 'TG', state_name: 'Telangana', gst_state_code: '36', is_union_territory: 0, is_active: 1 },
      { state_code: 'HR', state_name: 'Haryana', gst_state_code: '06', is_union_territory: 0, is_active: 1 },
      { state_code: 'PB', state_name: 'Punjab', gst_state_code: '03', is_union_territory: 0, is_active: 1 }
    ];

    const dialect = queryInterface.sequelize.getDialect ? queryInterface.sequelize.getDialect() : 'mysql';
    if (dialect === 'mysql' || dialect === 'mariadb') {
      for (const row of states) {
        await queryInterface.sequelize.query(
          `INSERT IGNORE INTO state (country_id, state_code, state_name, gst_state_code, is_union_territory, is_active, created_at, updated_at)
           VALUES (:country_id, :state_code, :state_name, :gst_state_code, :is_union_territory, :is_active, NOW(), NOW())`,
          { replacements: { country_id: indiaId, ...row } }
        );
      }
    } else {
      await queryInterface.bulkInsert('state', states.map((row) => ({
        country_id: indiaId,
        ...row,
        is_union_territory: !!row.is_union_territory,
        is_active: !!row.is_active,
        created_at: new Date(),
        updated_at: new Date()
      })), { ignoreDuplicates: true });
    }
  },

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

