'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [companies, plants, 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 plant WHERE code = 'PLANT001' 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 plantId = plants[0].length > 0 ? plants[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;

    await queryInterface.bulkInsert('gstin', [
      {
        company_id: companyId,
        plant_id: plantId,
        gstin: '27AAAAA0000A1Z5',
        trade_name: 'ABC Manufacturing',
        legal_name: 'ABC Manufacturing Private Limited',
        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',
        status: 'ACTIVE',
        is_primary: true,
        effective_from: '2020-01-01',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      }
    ]);
  },

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

