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

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

module.exports = class JobsDBApi {

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

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

        name: data.name
        ||
        null
            ,

        job_number: data.job_number
        ||
        null
            ,

        job_name: data.job_name
        ||
        null
            ,

        status: data.status
        ||
        null
            ,

        scheduled_completion_date: data.scheduled_completion_date
        ||
        null
            ,

        job_type: data.job_type
        ||
        null
            ,

        total_cost: data.total_cost
        ||
        null
            ,

        invoiced: data.invoiced
        ||
        null
            ,

        uninvoiced: data.uninvoiced
        ||
        null
            ,

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

        return jobs;
    }

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

                name: item.name
            ||
            null
            ,

                job_number: item.job_number
            ||
            null
            ,

                job_name: item.job_name
            ||
            null
            ,

                status: item.status
            ||
            null
            ,

                scheduled_completion_date: item.scheduled_completion_date
            ||
            null
            ,

                job_type: item.job_type
            ||
            null
            ,

                total_cost: item.total_cost
            ||
            null
            ,

                invoiced: item.invoiced
            ||
            null
            ,

                uninvoiced: item.uninvoiced
            ||
            null
            ,

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

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

        return jobs;
    }

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

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

        const updatePayload = {};

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

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

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

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

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

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

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

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

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

        updatePayload.updatedById = currentUser.id;

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

        return jobs;
    }

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

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

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

        return jobs;
    }

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

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

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

        await jobs.destroy({
            transaction
        });

        return jobs;
    }

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

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

        if (!jobs) {
            return jobs;
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }

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

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

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

};

