
const db = require('../models');
const crypto = require('crypto');
const Utils = require('../utils');

const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Payment_revenuesDBApi {

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

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

        transaction_date: data.transaction_date
        ||
        null
            ,

        admin_fee_amount: data.admin_fee_amount
        ||
        null
            ,

        interest_amount: data.interest_amount
        ||
        null
            ,

        commission_amount: data.commission_amount
        ||
        null
            ,

        expense_amount: data.expense_amount
        ||
        null
            ,

        setlement_datetime: data.setlement_datetime
        ||
        null
            ,

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

        return payment_revenues;
    }

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

                transaction_date: item.transaction_date
            ||
            null
            ,

                admin_fee_amount: item.admin_fee_amount
            ||
            null
            ,

                interest_amount: item.interest_amount
            ||
            null
            ,

                commission_amount: item.commission_amount
            ||
            null
            ,

                expense_amount: item.expense_amount
            ||
            null
            ,

                setlement_datetime: item.setlement_datetime
            ||
            null
            ,

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

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

        return payment_revenues;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return payment_revenues;
    }

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

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

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

        return payment_revenues;
    }

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

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

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

        await payment_revenues.destroy({
            transaction
        });

        return payment_revenues;
    }

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

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

        if (!payment_revenues) {
            return payment_revenues;
        }

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

        return output;
    }

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

        const user = (options && options.currentUser) || null;

        offset = currentPage * limit;

        const orderBy = null;

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

        let include = [];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

};

