'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    const [companies, departments, designations, cities, states, countries, 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 WHERE department_code = 'ADMIN' LIMIT 1"),
      queryInterface.sequelize.query("SELECT id FROM designation WHERE designation_code = 'CEO' 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 deptId = departments[0].length > 0 ? departments[0][0].id : null;
    const desgId = designations[0].length > 0 ? designations[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('employee', [
      {
        company_id: companyId,
        employee_number: 'EMP001',
        first_name: 'Rajesh',
        last_name: 'Kumar',
        date_of_birth: '1980-01-15',
        gender: 'MALE',
        pan_number: 'ABCDE1234F',
        department_id: deptId,
        designation_id: desgId,
        employee_type: 'PERMANENT',
        joining_date: '2020-01-01',
        confirmation_date: '2020-07-01',
        work_email: 'rajesh.kumar@abcmanufacturing.com',
        mobile_phone: '9876543210',
        address_line1: '123 Main Street',
        city_id: cityId,
        state_id: stateId,
        country_id: countryId,
        pincode: '400001',
        pf_contribution: true,
        esi_contribution: true,
        status: 'ACTIVE',
        created_by: userId,
        created_at: new Date(),
        updated_at: new Date()
      }
    ], { ignoreDuplicates: true });
  },

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

