const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');

const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class EmployeesDBApi {
  static async create(data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const employees = await db.employees.create(
      {
        id: data.id || undefined,

        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await employees.setUser(data.user || null, {
      transaction,
    });

    await employees.setOrganizations(data.organizations || null, {
      transaction,
    });

    await employees.setEmployments(data.employments || [], {
      transaction,
    });

    await employees.setPositions(data.positions || [], {
      transaction,
    });

    await employees.setCompensations(data.compensations || [], {
      transaction,
    });

    await employees.setDocuments(data.documents || [], {
      transaction,
    });

    return employees;
  }

  static async bulkImport(data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    // Prepare data - wrapping individual data transformations in a map() method
    const employeesData = data.map((item, index) => ({
      id: item.id || undefined,

      importHash: item.importHash || null,
      createdById: currentUser.id,
      updatedById: currentUser.id,
      createdAt: new Date(Date.now() + index * 1000),
    }));

    // Bulk create items
    const employees = await db.employees.bulkCreate(employeesData, {
      transaction,
    });

    // For each item created, replace relation files

    return employees;
  }

  static async update(id, data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;
    const globalAccess = currentUser.app_role?.globalAccess;

    const employees = await db.employees.findByPk(id, {}, { transaction });

    const updatePayload = {};

    updatePayload.updatedById = currentUser.id;

    await employees.update(updatePayload, { transaction });

    if (data.user !== undefined) {
      await employees.setUser(
        data.user,

        { transaction },
      );
    }

    if (data.organizations !== undefined) {
      await employees.setOrganizations(
        data.organizations,

        { transaction },
      );
    }

    if (data.employments !== undefined) {
      await employees.setEmployments(data.employments, { transaction });
    }

    if (data.positions !== undefined) {
      await employees.setPositions(data.positions, { transaction });
    }

    if (data.compensations !== undefined) {
      await employees.setCompensations(data.compensations, { transaction });
    }

    if (data.documents !== undefined) {
      await employees.setDocuments(data.documents, { transaction });
    }

    return employees;
  }

  static async deleteByIds(ids, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const employees = await db.employees.findAll({
      where: {
        id: {
          [Op.in]: ids,
        },
      },
      transaction,
    });

    await db.sequelize.transaction(async (transaction) => {
      for (const record of employees) {
        await record.update({ deletedBy: currentUser.id }, { transaction });
      }
      for (const record of employees) {
        await record.destroy({ transaction });
      }
    });

    return employees;
  }

  static async remove(id, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

    const employees = await db.employees.findByPk(id, options);

    await employees.update(
      {
        deletedBy: currentUser.id,
      },
      {
        transaction,
      },
    );

    await employees.destroy({
      transaction,
    });

    return employees;
  }

  static async findBy(where, options) {
    const transaction = (options && options.transaction) || undefined;

    const employees = await db.employees.findOne({ where }, { transaction });

    if (!employees) {
      return employees;
    }

    const output = employees.get({ plain: true });

    output.app_accounts_employee = await employees.getApp_accounts_employee({
      transaction,
    });

    output.approvals_approver = await employees.getApprovals_approver({
      transaction,
    });

    output.cards_employee = await employees.getCards_employee({
      transaction,
    });

    output.compensations_employee = await employees.getCompensations_employee({
      transaction,
    });

    output.deductions_employee = await employees.getDeductions_employee({
      transaction,
    });

    output.devices_owner = await employees.getDevices_owner({
      transaction,
    });

    output.documents_owner = await employees.getDocuments_owner({
      transaction,
    });

    output.earnings_employee = await employees.getEarnings_employee({
      transaction,
    });

    output.employments_employee = await employees.getEmployments_employee({
      transaction,
    });

    output.enrollment_learnings_employee =
      await employees.getEnrollment_learnings_employee({
        transaction,
      });

    output.enrollment_learnings_assigned_by =
      await employees.getEnrollment_learnings_assigned_by({
        transaction,
      });

    output.enrollments_employee = await employees.getEnrollments_employee({
      transaction,
    });

    output.expense_reports_employee =
      await employees.getExpense_reports_employee({
        transaction,
      });

    output.goals_employee = await employees.getGoals_employee({
      transaction,
    });

    output.identity_accounts_employee =
      await employees.getIdentity_accounts_employee({
        transaction,
      });

    output.interviews_interviewer = await employees.getInterviews_interviewer({
      transaction,
    });

    output.job_requisitions_recruiter =
      await employees.getJob_requisitions_recruiter({
        transaction,
      });

    output.leave_requests_employee = await employees.getLeave_requests_employee(
      {
        transaction,
      },
    );

    output.positions_manager = await employees.getPositions_manager({
      transaction,
    });

    output.reviews_employee = await employees.getReviews_employee({
      transaction,
    });

    output.reviews_reviewer = await employees.getReviews_reviewer({
      transaction,
    });

    output.schedule_shifts_employee =
      await employees.getSchedule_shifts_employee({
        transaction,
      });

    output.taxes_employee = await employees.getTaxes_employee({
      transaction,
    });

    output.timecards_employee = await employees.getTimecards_employee({
      transaction,
    });

    output.travel_bookings_employee =
      await employees.getTravel_bookings_employee({
        transaction,
      });

    output.user = await employees.getUser({
      transaction,
    });

    output.employments = await employees.getEmployments({
      transaction,
    });

    output.positions = await employees.getPositions({
      transaction,
    });

    output.compensations = await employees.getCompensations({
      transaction,
    });

    output.documents = await employees.getDocuments({
      transaction,
    });

    output.organizations = await employees.getOrganizations({
      transaction,
    });

    return output;
  }

  static async findAll(filter, globalAccess, options) {
    const limit = filter.limit || 0;
    let offset = 0;
    let where = {};
    const currentPage = +filter.page;

    const user = (options && options.currentUser) || null;
    const userOrganizations = (user && user.organizations?.id) || null;

    if (userOrganizations) {
      if (options?.currentUser?.organizationsId) {
        where.organizationsId = options.currentUser.organizationsId;
      }
    }

    offset = currentPage * limit;

    const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [
      {
        model: db.users,
        as: 'user',

        where: filter.user
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.user
                      .split('|')
                      .map((term) => Utils.uuid(term)),
                  },
                },
                {
                  firstName: {
                    [Op.or]: filter.user
                      .split('|')
                      .map((term) => ({ [Op.iLike]: `%${term}%` })),
                  },
                },
              ],
            }
          : {},
      },

      {
        model: db.organizations,
        as: 'organizations',
      },

      {
        model: db.employments,
        as: 'employments',
        required: false,
      },

      {
        model: db.positions,
        as: 'positions',
        required: false,
      },

      {
        model: db.compensations,
        as: 'compensations',
        required: false,
      },

      {
        model: db.documents,
        as: 'documents',
        required: false,
      },
    ];

    if (filter) {
      if (filter.id) {
        where = {
          ...where,
          ['id']: Utils.uuid(filter.id),
        };
      }

      if (filter.active !== undefined) {
        where = {
          ...where,
          active: filter.active === true || filter.active === 'true',
        };
      }

      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map((item) => {
          return Utils.uuid(item);
        });

        where = {
          ...where,
          organizationsId: { [Op.or]: listItems },
        };
      }

      if (filter.employments) {
        const searchTerms = filter.employments.split('|');

        include = [
          {
            model: db.employments,
            as: 'employments_filter',
            required: searchTerms.length > 0,
            where:
              searchTerms.length > 0
                ? {
                    [Op.or]: [
                      {
                        id: {
                          [Op.in]: searchTerms.map((term) => Utils.uuid(term)),
                        },
                      },
                      {
                        employment_type: {
                          [Op.or]: searchTerms.map((term) => ({
                            [Op.iLike]: `%${term}%`,
                          })),
                        },
                      },
                    ],
                  }
                : undefined,
          },
          ...include,
        ];
      }

      if (filter.positions) {
        const searchTerms = filter.positions.split('|');

        include = [
          {
            model: db.positions,
            as: 'positions_filter',
            required: searchTerms.length > 0,
            where:
              searchTerms.length > 0
                ? {
                    [Op.or]: [
                      {
                        id: {
                          [Op.in]: searchTerms.map((term) => Utils.uuid(term)),
                        },
                      },
                      {
                        title: {
                          [Op.or]: searchTerms.map((term) => ({
                            [Op.iLike]: `%${term}%`,
                          })),
                        },
                      },
                    ],
                  }
                : undefined,
          },
          ...include,
        ];
      }

      if (filter.compensations) {
        const searchTerms = filter.compensations.split('|');

        include = [
          {
            model: db.compensations,
            as: 'compensations_filter',
            required: searchTerms.length > 0,
            where:
              searchTerms.length > 0
                ? {
                    [Op.or]: [
                      {
                        id: {
                          [Op.in]: searchTerms.map((term) => Utils.uuid(term)),
                        },
                      },
                      {
                        base_pay: {
                          [Op.or]: searchTerms.map((term) => ({
                            [Op.iLike]: `%${term}%`,
                          })),
                        },
                      },
                    ],
                  }
                : undefined,
          },
          ...include,
        ];
      }

      if (filter.documents) {
        const searchTerms = filter.documents.split('|');

        include = [
          {
            model: db.documents,
            as: 'documents_filter',
            required: searchTerms.length > 0,
            where:
              searchTerms.length > 0
                ? {
                    [Op.or]: [
                      {
                        id: {
                          [Op.in]: searchTerms.map((term) => Utils.uuid(term)),
                        },
                      },
                      {
                        doc_type: {
                          [Op.or]: searchTerms.map((term) => ({
                            [Op.iLike]: `%${term}%`,
                          })),
                        },
                      },
                    ],
                  }
                : undefined,
          },
          ...include,
        ];
      }

      if (filter.createdAtRange) {
        const [start, end] = filter.createdAtRange;

        if (start !== undefined && start !== null && start !== '') {
          where = {
            ...where,
            ['createdAt']: {
              ...where.createdAt,
              [Op.gte]: start,
            },
          };
        }

        if (end !== undefined && end !== null && end !== '') {
          where = {
            ...where,
            ['createdAt']: {
              ...where.createdAt,
              [Op.lte]: end,
            },
          };
        }
      }
    }

    if (globalAccess) {
      delete where.organizationsId;
    }

    const queryOptions = {
      where,
      include,
      distinct: true,
      order:
        filter.field && filter.sort
          ? [[filter.field, filter.sort]]
          : [['createdAt', 'desc']],
      transaction: options?.transaction,
      logging: console.log,
    };

    if (!options?.countOnly) {
      queryOptions.limit = limit ? Number(limit) : undefined;
      queryOptions.offset = offset ? Number(offset) : undefined;
    }

    try {
      const { rows, count } = await db.employees.findAndCountAll(queryOptions);

      return {
        rows: options?.countOnly ? [] : rows,
        count: count,
      };
    } catch (error) {
      console.error('Error executing query:', error);
      throw error;
    }
  }

  static async findAllAutocomplete(
    query,
    limit,
    offset,
    globalAccess,
    organizationId,
  ) {
    let where = {};

    if (!globalAccess && organizationId) {
      where.organizationId = organizationId;
    }

    if (query) {
      where = {
        [Op.or]: [
          { ['id']: Utils.uuid(query) },
          Utils.ilike('employees', 'user', query),
        ],
      };
    }

    const records = await db.employees.findAll({
      attributes: ['id', 'user'],
      where,
      limit: limit ? Number(limit) : undefined,
      offset: offset ? Number(offset) : undefined,
      orderBy: [['user', 'ASC']],
    });

    return records.map((record) => ({
      id: record.id,
      label: record.user,
    }));
  }
};
