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

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

module.exports = class Interest_ratesDBApi {

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

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

        code: data.code
        ||
        null
            ,

        name: data.name
        ||
        null
            ,

        rate: data.rate
        ||
        null
            ,

        commission_rate: data.commission_rate
        ||
        null
            ,

        interval: data.interval
        ||
        null
            ,

        sort: data.sort
        ||
        null
            ,

        css: data.css
        ||
        null
            ,

        setting: data.setting
        ||
        null
            ,

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

        return interest_rates;
    }

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

                code: item.code
            ||
            null
            ,

                name: item.name
            ||
            null
            ,

                rate: item.rate
            ||
            null
            ,

                commission_rate: item.commission_rate
            ||
            null
            ,

                interval: item.interval
            ||
            null
            ,

                sort: item.sort
            ||
            null
            ,

                css: item.css
            ||
            null
            ,

                setting: item.setting
            ||
            null
            ,

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

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

        return interest_rates;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return interest_rates;
    }

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

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

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

        return interest_rates;
    }

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

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

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

        await interest_rates.destroy({
            transaction
        });

        return interest_rates;
    }

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

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

        if (!interest_rates) {
            return interest_rates;
        }

        const output = interest_rates.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(
                            'interest_rates',
                            'code',
                            filter.code,
                        ),
                    };
                }

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

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

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

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

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

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

};

