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

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

        date: data.date || null,
        merchant: data.merchant || null,
        amount: data.amount || null,
        currency: data.currency || null,
        category: data.category || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await expense_lines.setReport(data.report || null, {
      transaction,
    });

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

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: db.expense_lines.getTableName(),
        belongsToColumn: 'receipt_ref',
        belongsToId: expense_lines.id,
      },
      data.receipt_ref,
      options,
    );

    return expense_lines;
  }

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

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

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

    // For each item created, replace relation files

    for (let i = 0; i < expense_lines.length; i++) {
      await FileDBApi.replaceRelationFiles(
        {
          belongsTo: db.expense_lines.getTableName(),
          belongsToColumn: 'receipt_ref',
          belongsToId: expense_lines[i].id,
        },
        data[i].receipt_ref,
        options,
      );
    }

    return expense_lines;
  }

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

    const updatePayload = {};

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.report !== undefined) {
      await expense_lines.setReport(
        data.report,

        { transaction },
      );
    }

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

        { transaction },
      );
    }

    await FileDBApi.replaceRelationFiles(
      {
        belongsTo: db.expense_lines.getTableName(),
        belongsToColumn: 'receipt_ref',
        belongsToId: expense_lines.id,
      },
      data.receipt_ref,
      options,
    );

    return expense_lines;
  }

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

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

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

    return expense_lines;
  }

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

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

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

    await expense_lines.destroy({
      transaction,
    });

    return expense_lines;
  }

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

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

    if (!expense_lines) {
      return expense_lines;
    }

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

    output.report = await expense_lines.getReport({
      transaction,
    });

    output.receipt_ref = await expense_lines.getReceipt_ref({
      transaction,
    });

    output.organizations = await expense_lines.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.expense_reports,
        as: 'report',

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

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

      {
        model: db.file,
        as: 'receipt_ref',
      },
    ];

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

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

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

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

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

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

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

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

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

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

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

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

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