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

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

        label: data.label || null,
        url: data.url || null,
        icon: data.icon || null,
        enabled: data.enabled || false,

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

    await button_links.setBlock(data.block || null, {
      transaction,
    });

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

    return button_links;
  }

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

      label: item.label || null,
      url: item.url || null,
      icon: item.icon || null,
      enabled: item.enabled || false,

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

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

    // For each item created, replace relation files

    return button_links;
  }

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

    const updatePayload = {};

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

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.block !== undefined) {
      await button_links.setBlock(
        data.block,

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    return button_links;
  }

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

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

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

    return button_links;
  }

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

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

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

    await button_links.destroy({
      transaction,
    });

    return button_links;
  }

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

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

    if (!button_links) {
      return button_links;
    }

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

    output.analytics_events_link = await button_links.getAnalytics_events_link({
      transaction,
    });

    output.block = await button_links.getBlock({
      transaction,
    });

    output.organizations = await button_links.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.blocks,
        as: 'block',

        where: filter.block
          ? {
              [Op.or]: [
                {
                  id: {
                    [Op.in]: filter.block
                      .split('|')
                      .map((term) => Utils.uuid(term)),
                  },
                },
                {
                  type: {
                    [Op.or]: filter.block
                      .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.label) {
        where = {
          ...where,
          [Op.and]: Utils.ilike('button_links', 'label', filter.label),
        };
      }

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

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

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

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

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

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

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

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

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

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

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

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

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