
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 Service_requestsDBApi {
    

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

        const service_requests = await db.service_requests.create(
            {
                id: data.id || undefined,
        
        service_type: data.service_type
        ||
        null
            ,
            
        timing_preference: data.timing_preference
        ||
        null
            ,
            
        scheduled_start_at: data.scheduled_start_at
        ||
        null
            ,
            
        scheduled_end_at: data.scheduled_end_at
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        priority: data.priority
        ||
        null
            ,
            
        estimated_total: data.estimated_total
        ||
        null
            ,
            
        final_total: data.final_total
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
        requires_no_contact_coordination: data.requires_no_contact_coordination
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await service_requests.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await service_requests.setCustomer( data.customer || null, {
            transaction,
        });
        
        await service_requests.setRequester_user( data.requester_user || null, {
            transaction,
        });
        
        await service_requests.setAssigned_coordinator_user( data.assigned_coordinator_user || null, {
            transaction,
        });
        
        await service_requests.setService_package( data.service_package || null, {
            transaction,
        });
        

        

        

        return service_requests;
    }
    

    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 service_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                service_type: item.service_type
            ||
            null
            ,
            
                timing_preference: item.timing_preference
            ||
            null
            ,
            
                scheduled_start_at: item.scheduled_start_at
            ||
            null
            ,
            
                scheduled_end_at: item.scheduled_end_at
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                priority: item.priority
            ||
            null
            ,
            
                estimated_total: item.estimated_total
            ||
            null
            ,
            
                final_total: item.final_total
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
                requires_no_contact_coordination: item.requires_no_contact_coordination
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return service_requests;
    }

    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 service_requests = await db.service_requests.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.service_type !== undefined) updatePayload.service_type = data.service_type;
        
        
        if (data.timing_preference !== undefined) updatePayload.timing_preference = data.timing_preference;
        
        
        if (data.scheduled_start_at !== undefined) updatePayload.scheduled_start_at = data.scheduled_start_at;
        
        
        if (data.scheduled_end_at !== undefined) updatePayload.scheduled_end_at = data.scheduled_end_at;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        if (data.estimated_total !== undefined) updatePayload.estimated_total = data.estimated_total;
        
        
        if (data.final_total !== undefined) updatePayload.final_total = data.final_total;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        if (data.requires_no_contact_coordination !== undefined) updatePayload.requires_no_contact_coordination = data.requires_no_contact_coordination;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await service_requests.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await service_requests.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.requester_user !== undefined) {
            await service_requests.setRequester_user(
              
              data.requester_user,
              
              { transaction }
            );
        }
        
        if (data.assigned_coordinator_user !== undefined) {
            await service_requests.setAssigned_coordinator_user(
              
              data.assigned_coordinator_user,
              
              { transaction }
            );
        }
        
        if (data.service_package !== undefined) {
            await service_requests.setService_package(
              
              data.service_package,
              
              { transaction }
            );
        }
        

        
        

        

        return service_requests;
    }

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

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

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


        return service_requests;
    }

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

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

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

        await service_requests.destroy({
            transaction
        });

        return service_requests;
    }

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

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

        if (!service_requests) {
            return service_requests;
        }

        const output = service_requests.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        output.service_request_add_ons_service_request = await service_requests.getService_request_add_ons_service_request({
            transaction
        });
        
        
        output.request_checklist_items_service_request = await service_requests.getRequest_checklist_items_service_request({
            transaction
        });
        
        
        output.request_timeline_events_service_request = await service_requests.getRequest_timeline_events_service_request({
            transaction
        });
        
        
        output.request_documents_service_request = await service_requests.getRequest_documents_service_request({
            transaction
        });
        
        
        output.chat_threads_service_request = await service_requests.getChat_threads_service_request({
            transaction
        });
        
        
        
        output.payment_transactions_service_request = await service_requests.getPayment_transactions_service_request({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await service_requests.getOrganization({
            transaction
        });
        
        
        output.customer = await service_requests.getCustomer({
            transaction
        });
        
        
        output.requester_user = await service_requests.getRequester_user({
            transaction
        });
        
        
        output.assigned_coordinator_user = await service_requests.getAssigned_coordinator_user({
            transaction
        });
        
        
        output.service_package = await service_requests.getService_package({
            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.organizations,
        as: 'organization',
        
      },

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

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

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

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



    ];

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

            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'service_requests',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'service_requests',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.service_type) {
                where = {
                    ...where,
                service_type: filter.service_type,
            };
            }
            
            if (filter.timing_preference) {
                where = {
                    ...where,
                timing_preference: filter.timing_preference,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.priority) {
                where = {
                    ...where,
                priority: filter.priority,
            };
            }
            
            if (filter.requires_no_contact_coordination) {
                where = {
                    ...where,
                requires_no_contact_coordination: filter.requires_no_contact_coordination,
            };
            }
            


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

        where = {
          ...where,
          organizationId: {[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.service_requests.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(
                        'service_requests',
                        'summary',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

