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

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

module.exports = class QuotesDBApi {

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

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

        name: data.name
        ||
        null
            ,

        status: data.status
        ||
        null
            ,

        quote_title: data.quote_title
        ||
        null
            ,

        total_quoted: data.total_quoted
        ||
        null
            ,

        estimated_profit: data.estimated_profit
        ||
        null
            ,

        created_date: data.created_date
        ||
        null
            ,

        last_modified_date: data.last_modified_date
        ||
        null
            ,

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

        return quotes;
    }

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

                name: item.name
            ||
            null
            ,

                status: item.status
            ||
            null
            ,

                quote_title: item.quote_title
            ||
            null
            ,

                total_quoted: item.total_quoted
            ||
            null
            ,

                estimated_profit: item.estimated_profit
            ||
            null
            ,

                created_date: item.created_date
            ||
            null
            ,

                last_modified_date: item.last_modified_date
            ||
            null
            ,

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

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

        return quotes;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return quotes;
    }

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

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

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

        return quotes;
    }

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

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

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

        await quotes.destroy({
            transaction
        });

        return quotes;
    }

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

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

        if (!quotes) {
            return quotes;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

};

