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

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

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

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

    return patient_messages;
  }

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

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

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

    // For each item created, replace relation files

    return patient_messages;
  }

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

    const updatePayload = {};

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

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

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

    updatePayload.updatedById = currentUser.id;

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

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

        { transaction },
      );
    }

    return patient_messages;
  }

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

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

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

    return patient_messages;
  }

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

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

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

    await patient_messages.destroy({
      transaction,
    });

    return patient_messages;
  }

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

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

    if (!patient_messages) {
      return patient_messages;
    }

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

    output.organizations = await patient_messages.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: 'organizations',
      },
    ];

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

      if (filter.sender) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('patient_messages', 'sender', filter.sender),
        };
      }

      if (filter.message) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('patient_messages', 'message', filter.message),
        };
      }

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

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

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

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

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