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 Onboarding_casesDBApi {
  static async create(data, options) {
    const currentUser = (options && options.currentUser) || { id: null };
    const transaction = (options && options.transaction) || undefined;

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

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

    await onboarding_cases.setOrganization(
      currentUser.organization.id || null,
      {
        transaction,
      },
    );

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

    await onboarding_cases.setAssigned_staff(data.assigned_staff || null, {
      transaction,
    });

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

    return onboarding_cases;
  }

  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 onboarding_casesData = data.map((item, index) => ({
      id: item.id || undefined,

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

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

    // For each item created, replace relation files

    return onboarding_cases;
  }

  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 onboarding_cases = await db.onboarding_cases.findByPk(
      id,
      {},
      { transaction },
    );

    const updatePayload = {};

    if (data.role !== undefined) updatePayload.role = data.role;

    if (data.status !== undefined) updatePayload.status = data.status;

    if (data.start_date !== undefined)
      updatePayload.start_date = data.start_date;

    if (data.completion_date !== undefined)
      updatePayload.completion_date = data.completion_date;

    updatePayload.updatedById = currentUser.id;

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

    if (data.organization !== undefined) {
      await onboarding_cases.setOrganization(
        globalAccess ? data.organization : currentUser.organization.id,
        { transaction },
      );
    }

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

        { transaction },
      );
    }

    if (data.assigned_staff !== undefined) {
      await onboarding_cases.setAssigned_staff(
        data.assigned_staff,

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    return onboarding_cases;
  }

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

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

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

    return onboarding_cases;
  }

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

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

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

    await onboarding_cases.destroy({
      transaction,
    });

    return onboarding_cases;
  }

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

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

    if (!onboarding_cases) {
      return onboarding_cases;
    }

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

    output.organization = await onboarding_cases.getOrganization({
      transaction,
    });

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

    output.assigned_staff = await onboarding_cases.getAssigned_staff({
      transaction,
    });

    output.organizations = await onboarding_cases.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.organizations,
        as: 'organization',
      },

      {
        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.users,
        as: 'assigned_staff',

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

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

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

      if (filter.calendarStart && filter.calendarEnd) {
        where = {
          ...where,
          [Op.or]: [
            {
              start_date: {
                [Op.between]: [filter.calendarStart, filter.calendarEnd],
              },
            },
            {
              completion_date: {
                [Op.between]: [filter.calendarStart, filter.calendarEnd],
              },
            },
          ],
        };
      }

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

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

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

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

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

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

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

      if (filter.role) {
        where = {
          ...where,
          role: filter.role,
        };
      }

      if (filter.status) {
        where = {
          ...where,
          status: filter.status,
        };
      }

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

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

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

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

      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.onboarding_cases.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('onboarding_cases', 'user', query),
        ],
      };
    }

    const records = await db.onboarding_cases.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,
    }));
  }
};
