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

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

module.exports = class LoansDBApi {

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

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

        code: data.code
        ||
        null
            ,

        principal_amount: data.principal_amount
        ||
        null
            ,

        term: data.term
        ||
        null
            ,

        pending_amount: data.pending_amount
        ||
        null
            ,

        last_pending_amount: data.last_pending_amount
        ||
        null
            ,

        rate: data.rate
        ||
        null
            ,

        commission_rate: data.commission_rate
        ||
        null
            ,

        registration_date: data.registration_date
        ||
        null
            ,

        started_payment_date: data.started_payment_date
        ||
        null
            ,

        last_payment_date: data.last_payment_date
        ||
        null
            ,

        finish_payment_date: data.finish_payment_date
        ||
        null
            ,

        finish_discount: data.finish_discount
        ||
        null
            ,

        finish_discount_amount: data.finish_discount_amount
        ||
        null
            ,

        admin_rate: data.admin_rate
        ||
        null
            ,

        admin_amount: data.admin_amount
        ||
        null
            ,

        purpose: data.purpose
        ||
        null
            ,

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

        return loans;
    }

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

                code: item.code
            ||
            null
            ,

                principal_amount: item.principal_amount
            ||
            null
            ,

                term: item.term
            ||
            null
            ,

                pending_amount: item.pending_amount
            ||
            null
            ,

                last_pending_amount: item.last_pending_amount
            ||
            null
            ,

                rate: item.rate
            ||
            null
            ,

                commission_rate: item.commission_rate
            ||
            null
            ,

                registration_date: item.registration_date
            ||
            null
            ,

                started_payment_date: item.started_payment_date
            ||
            null
            ,

                last_payment_date: item.last_payment_date
            ||
            null
            ,

                finish_payment_date: item.finish_payment_date
            ||
            null
            ,

                finish_discount: item.finish_discount
            ||
            null
            ,

                finish_discount_amount: item.finish_discount_amount
            ||
            null
            ,

                admin_rate: item.admin_rate
            ||
            null
            ,

                admin_amount: item.admin_amount
            ||
            null
            ,

                purpose: item.purpose
            ||
            null
            ,

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

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

        return loans;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return loans;
    }

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

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

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

        return loans;
    }

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

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

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

        await loans.destroy({
            transaction
        });

        return loans;
    }

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

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

        if (!loans) {
            return loans;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    admin_amount: {
                    ...where.admin_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.loans.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(
                        'loans',
                        'code',
                        query,
                    ),
                ],
            };
        }

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

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

};

