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

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

          name: data.name || null,
          rate_type: data.rate_type || null,
          standard_service: data.standard_service || null,
          service_text: data.service_text || null,
          rate: data.rate || null,
          service_id: data.service_id || null,
          service_code: data.service_code || null,
          unit_type: data.unit_type || null,
          cost: data.cost || null,
          qty: data.qty || null,
          currency: data.currency || null,
          rate_gbp: data.rate_gbp || null,
          rate_eur: data.rate_eur || null,
          rate_usd: data.rate_usd || null,
          yes_fixed_text: data.yes_fixed_text || false,

          no_fixed_text: data.no_fixed_text || false,

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

    await default_activities_products.setDepartment(data.department || null, {
      transaction,
    });

    return default_activities_products;
  }

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

      name: item.name || null,
      rate_type: item.rate_type || null,
      standard_service: item.standard_service || null,
      service_text: item.service_text || null,
      rate: item.rate || null,
      service_id: item.service_id || null,
      service_code: item.service_code || null,
      unit_type: item.unit_type || null,
      cost: item.cost || null,
      qty: item.qty || null,
      currency: item.currency || null,
      rate_gbp: item.rate_gbp || null,
      rate_eur: item.rate_eur || null,
      rate_usd: item.rate_usd || null,
      yes_fixed_text: item.yes_fixed_text || false,

      no_fixed_text: item.no_fixed_text || false,

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

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

    // For each item created, replace relation files

    return default_activities_products;
  }

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

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

    const updatePayload = {};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.department !== undefined) {
      await default_activities_products.setDepartment(
        data.department,

        { transaction },
      );
    }

    return default_activities_products;
  }

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

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

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

    return default_activities_products;
  }

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

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

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

    await default_activities_products.destroy({
      transaction,
    });

    return default_activities_products;
  }

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

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

    if (!default_activities_products) {
      return default_activities_products;
    }

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

    output.department = await default_activities_products.getDepartment({
      transaction,
    });

    return output;
  }

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

    offset = currentPage * limit;

    const orderBy = null;

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

    let include = [
      {
        model: db.departments,
        as: 'department',

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      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,
            },
          };
        }
      }
    }

    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.default_activities_products.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) {
    let where = {};

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

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

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