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

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

module.exports = class Payment_transactionsDBApi {

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

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

        transaction_datetime: data.transaction_datetime
        ||
        null
            ,

        transaction_amount: data.transaction_amount
        ||
        null
            ,

        deduct_amount: data.deduct_amount
        ||
        null
            ,

        interest_amount: data.interest_amount
        ||
        null
            ,

        commission_amount: data.commission_amount
        ||
        null
            ,

        revenue_amount: data.revenue_amount
        ||
        null
            ,

        setlement_datetime: data.setlement_datetime
        ||
        null
            ,

        type: data.type
        ||
        null
            ,

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

        return payment_transactions;
    }

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

                transaction_datetime: item.transaction_datetime
            ||
            null
            ,

                transaction_amount: item.transaction_amount
            ||
            null
            ,

                deduct_amount: item.deduct_amount
            ||
            null
            ,

                interest_amount: item.interest_amount
            ||
            null
            ,

                commission_amount: item.commission_amount
            ||
            null
            ,

                revenue_amount: item.revenue_amount
            ||
            null
            ,

                setlement_datetime: item.setlement_datetime
            ||
            null
            ,

                type: item.type
            ||
            null
            ,

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

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

        return payment_transactions;
    }

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

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

        const updatePayload = {};

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

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

        if (data.deduct_amount !== undefined) updatePayload.deduct_amount = data.deduct_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.revenue_amount !== undefined) updatePayload.revenue_amount = data.revenue_amount;

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

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

        updatePayload.updatedById = currentUser.id;

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

        return payment_transactions;
    }

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

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

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

        return payment_transactions;
    }

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

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

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

        await payment_transactions.destroy({
            transaction
        });

        return payment_transactions;
    }

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

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

        if (!payment_transactions) {
            return payment_transactions;
        }

        const output = payment_transactions.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_datetimeRange) {
                const [start, end] = filter.transaction_datetimeRange;

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    deduct_amount: {
                    ...where.deduct_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.revenue_amountRange) {
                const [start, end] = filter.revenue_amountRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    revenue_amount: {
                    ...where.revenue_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.type) {
                where = {
                    ...where,
                type: filter.type,
            };
            }

            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_transactions.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_transactions',
                        'transaction_amount',
                        query,
                    ),
                ],
            };
        }

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

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

};

