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

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

        amount_paid: data.amount_paid || null,
        payment_date: data.payment_date || null,
        receipt_url: data.receipt_url || null,
        term: data.term || null,
        status: data.status || null,
        importHash: data.importHash || null,
        createdById: currentUser.id,
        updatedById: currentUser.id,
      },
      { transaction },
    );

    await fee_payments.setStudent(data.student || null, {
      transaction,
    });

    await fee_payments.setSchools(data.schools || null, {
      transaction,
    });

    return fee_payments;
  }

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

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

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

    // For each item created, replace relation files

    return fee_payments;
  }

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

    const updatePayload = {};

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

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

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

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

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

    updatePayload.updatedById = currentUser.id;

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

    if (data.student !== undefined) {
      await fee_payments.setStudent(
        data.student,

        { transaction },
      );
    }

    if (data.schools !== undefined) {
      await fee_payments.setSchools(
        data.schools,

        { transaction },
      );
    }

    return fee_payments;
  }

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

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

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

    return fee_payments;
  }

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

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

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

    await fee_payments.destroy({
      transaction,
    });

    return fee_payments;
  }

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

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

    if (!fee_payments) {
      return fee_payments;
    }

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

    output.student = await fee_payments.getStudent({
      transaction,
    });

    output.schools = await fee_payments.getSchools({
      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 userSchools = (user && user.schools?.id) || null;

    if (userSchools) {
      if (options?.currentUser?.schoolsId) {
        where.schoolsId = options.currentUser.schoolsId;
      }
    }

    offset = currentPage * limit;

    const orderBy = null;

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

    let include = [
      {
        model: db.students,
        as: 'student',

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        where = {
          ...where,
          schoolsId: { [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.schoolsId;
    }

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

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

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