
const db = require('../models');
const FileDBApi = require('./file');
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,
        
        title: data.title
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        estimated_duration_minutes: data.estimated_duration_minutes
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
        internal_notes: data.internal_notes
        ||
        null
            ,
            
        requires_invoice: data.requires_invoice
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await jobs.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await jobs.setCustomer( data.customer || null, {
            transaction,
        });
        
        await jobs.setProperty( data.property || null, {
            transaction,
        });
        
        await jobs.setService_catalog_item( data.service_catalog_item || null, {
            transaction,
        });
        
        await jobs.setOrganizations( data.organizations || null, {
            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,
                
                title: item.title
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                estimated_duration_minutes: item.estimated_duration_minutes
            ||
            null
            ,
            
                price: item.price
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
                internal_notes: item.internal_notes
            ||
            null
            ,
            
                requires_invoice: item.requires_invoice
            ||
            false
        
            ,
            
            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 });

        // For each item created, replace relation files
        

        return jobs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.estimated_duration_minutes !== undefined) updatePayload.estimated_duration_minutes = data.estimated_duration_minutes;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        if (data.internal_notes !== undefined) updatePayload.internal_notes = data.internal_notes;
        
        
        if (data.requires_invoice !== undefined) updatePayload.requires_invoice = data.requires_invoice;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await jobs.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await jobs.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.property !== undefined) {
            await jobs.setProperty(
              
              data.property,
              
              { transaction }
            );
        }
        
        if (data.service_catalog_item !== undefined) {
            await jobs.setService_catalog_item(
              
              data.service_catalog_item,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await jobs.setOrganizations(
              
              data.organizations,
              
              { 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});

        
        
        
        
        
        
        
        
        
        
        
        
        output.job_assignments_job = await jobs.getJob_assignments_job({
            transaction
        });
        
        
        
        
        output.job_checklist_runs_job = await jobs.getJob_checklist_runs_job({
            transaction
        });
        
        
        
        output.job_media_job = await jobs.getJob_media_job({
            transaction
        });
        
        
        output.invoices_job = await jobs.getInvoices_job({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.workspace = await jobs.getWorkspace({
            transaction
        });
        
        
        output.customer = await jobs.getCustomer({
            transaction
        });
        
        
        output.property = await jobs.getProperty({
            transaction
        });
        
        
        output.service_catalog_item = await jobs.getService_catalog_item({
            transaction
        });
        
        
        output.organizations = await jobs.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.customers,
        as: 'customer',
        
        where: filter.customer ? {
          [Op.or]: [
            { id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.customer.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.properties,
        as: 'property',
        
        where: filter.property ? {
          [Op.or]: [
            { id: { [Op.in]: filter.property.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.property.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.service_catalog_items,
        as: 'service_catalog_item',
        
        where: filter.service_catalog_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.service_catalog_item.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.service_catalog_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    start_at: {
                    ...where.start_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.end_atRange) {
                const [start, end] = filter.end_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    end_at: {
                    ...where.end_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.estimated_duration_minutesRange) {
                const [start, end] = filter.estimated_duration_minutesRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    estimated_duration_minutes: {
                    ...where.estimated_duration_minutes,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.priceRange) {
                const [start, end] = filter.priceRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    price: {
                    ...where.price,
                            [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.requires_invoice) {
                where = {
                    ...where,
                requires_invoice: filter.requires_invoice,
            };
            }
            


      

      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'jobs',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

