'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [companies, departments, currencies, users] = await Promise.all([
      queryInterface.sequelize.query("SELECT id FROM company WHERE code = 'COMP001' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id, department_code FROM department"),
      queryInterface.sequelize.query("SELECT id FROM currency WHERE currency_code = 'INR' 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 currencyId = currencies[0].length > 0 ? currencies[0][0].id : null;
    const userId = users[0][0].id;

    const deptMap = {};
    departments[0].forEach(dept => {
      deptMap[dept.department_code] = dept.id;
    });

    await queryInterface.bulkInsert('cost_center', [
      {
        company_id: companyId,
        cost_center_code: 'CC001',
        description: 'Production Cost Center',
        cost_center_type: 'PRODUCTION',
        department_id: deptMap['PROD'] || null,
        currency_id: currencyId,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        company_id: companyId,
        cost_center_code: 'CC002',
        description: 'Purchase Cost Center',
        cost_center_type: 'ADMINISTRATION',
        department_id: deptMap['PUR'] || null,
        currency_id: currencyId,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        company_id: companyId,
        cost_center_code: 'CC003',
        description: 'Sales Cost Center',
        cost_center_type: 'SALES',
        department_id: deptMap['SAL'] || null,
        currency_id: currencyId,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        company_id: companyId,
        cost_center_code: 'CC004',
        description: 'Finance Cost Center',
        cost_center_type: 'ADMINISTRATION',
        department_id: deptMap['FIN'] || null,
        currency_id: currencyId,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      }
    ], { ignoreDuplicates: true });
  },

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

