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

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

module.exports = class PaymentsDBApi {

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

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

        start_payment_date: data.start_payment_date
        ||
        null
            ,

        payment_date: data.payment_date
        ||
        null
            ,

        last_payment_paid_date: data.last_payment_paid_date
        ||
        null
            ,

        sort: data.sort
        ||
        null
            ,

        deduct_amount: data.deduct_amount
        ||
        null
            ,

        deduct_paid_amount: data.deduct_paid_amount
        ||
        null
            ,

        interval: data.interval
        ||
        null
            ,

        interest_amount: data.interest_amount
        ||
        null
            ,

        commission_amount: data.commission_amount
        ||
        null
            ,

        total_amount: data.total_amount
        ||
        null
            ,

        total_paid_amount: data.total_paid_amount
        ||
        null
            ,

        penalty_amount: data.penalty_amount
        ||
        null
            ,

        pending_amount: data.pending_amount
        ||
        null
            ,

        cross_amount: data.cross_amount
        ||
        null
            ,

        remark: data.remark
        ||
        null
            ,

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

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

                start_payment_date: item.start_payment_date
            ||
            null
            ,

                payment_date: item.payment_date
            ||
            null
            ,

                last_payment_paid_date: item.last_payment_paid_date
            ||
            null
            ,

                sort: item.sort
            ||
            null
            ,

                deduct_amount: item.deduct_amount
            ||
            null
            ,

                deduct_paid_amount: item.deduct_paid_amount
            ||
            null
            ,

                interval: item.interval
            ||
            null
            ,

                interest_amount: item.interest_amount
            ||
            null
            ,

                commission_amount: item.commission_amount
            ||
            null
            ,

                total_amount: item.total_amount
            ||
            null
            ,

                total_paid_amount: item.total_paid_amount
            ||
            null
            ,

                penalty_amount: item.penalty_amount
            ||
            null
            ,

                pending_amount: item.pending_amount
            ||
            null
            ,

                cross_amount: item.cross_amount
            ||
            null
            ,

                remark: item.remark
            ||
            null
            ,

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

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

        return payments;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return payments;
    }

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

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

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

        return payments;
    }

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

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

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

        await payments.destroy({
            transaction
        });

        return payments;
    }

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

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

        if (!payments) {
            return payments;
        }

        const output = payments.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.remark) {
                    where = {
                        ...where,
                        [Op.and]: Utils.ilike(
                            'payments',
                            'remark',
                            filter.remark,
                        ),
                    };
                }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    cross_amount: {
                    ...where.cross_amount,
                            [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.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) {
        let where = {};

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

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

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

};

