'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [companies, currencies, glAccounts, users] = await Promise.all([
      queryInterface.sequelize.query("SELECT id FROM company WHERE code = 'COMP001' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id FROM currency WHERE currency_code = 'INR' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id, account_code FROM gl_account WHERE account_code IN ('1111', '2111')"),
      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 currencyId = currencies[0].length > 0 ? currencies[0][0].id : null;
    const debtorAccountId = glAccounts[0].find(acc => acc.account_code === '1111')?.id || null;
    const creditorAccountId = glAccounts[0].find(acc => acc.account_code === '2111')?.id || null;

    await queryInterface.bulkInsert('business_partner', [
      {
        company_id: companyId,
        bp_number: 'BP001',
        bp_type: 'CUSTOMER',
        name: 'XYZ Corporation',
        legal_name: 'XYZ Corporation Private Limited',
        pan: 'XYZZZ1234Z',
        tax_category: 'REGULAR',
        payment_terms: 30,
        credit_limit: 1000000.00,
        currency_id: currencyId,
        gl_account_id: debtorAccountId,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        company_id: companyId,
        bp_number: 'BP002',
        bp_type: 'VENDOR',
        name: 'ABC Suppliers',
        legal_name: 'ABC Suppliers Private Limited',
        pan: 'ABCDE5678E',
        tax_category: 'REGULAR',
        payment_terms: 45,
        credit_limit: 500000.00,
        currency_id: currencyId,
        gl_account_id: creditorAccountId,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        company_id: companyId,
        bp_number: 'BP003',
        bp_type: 'BOTH',
        name: 'DEF Trading Company',
        legal_name: 'DEF Trading Company Private Limited',
        pan: 'DEFGH9012H',
        tax_category: 'REGULAR',
        payment_terms: 30,
        credit_limit: 750000.00,
        currency_id: currencyId,
        gl_account_id: debtorAccountId,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      }
    ]);
  },

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

