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

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

module.exports = class Expense_itemsDBApi {

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

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

        expense_datetime: data.expense_datetime
        ||
        null
            ,

        description: data.description
        ||
        null
            ,

        expense_amount: data.expense_amount
        ||
        null
            ,

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

        return expense_items;
    }

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

                expense_datetime: item.expense_datetime
            ||
            null
            ,

                description: item.description
            ||
            null
            ,

                expense_amount: item.expense_amount
            ||
            null
            ,

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

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

        return expense_items;
    }

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

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

        const updatePayload = {};

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return expense_items;
    }

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

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

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

        return expense_items;
    }

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

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

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

        await expense_items.destroy({
            transaction
        });

        return expense_items;
    }

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

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

        if (!expense_items) {
            return expense_items;
        }

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    expense_datetime: {
                    ...where.expense_datetime,
                            [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.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.expense_items.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(
                        'expense_items',
                        'description',
                        query,
                    ),
                ],
            };
        }

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

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

};

