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


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

function isCustomerUser(currentUser) {
    return currentUser?.app_role?.name === config.roles.customer;
}

function mergeWhereWithScope(where, scope) {
    if (!scope) {
        return where;
    }

    return {
        [Op.and]: [where, scope],
    };
}

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,
        
        request_type: data.request_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        priority: data.priority
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        details: data.details
        ||
        null
            ,
            
        estimated_cost: data.estimated_cost
        ||
        null
            ,
            
        actual_cost: data.actual_cost
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await service_requests.setTenant( data.tenant || null, {
            transaction,
        });
        
        await service_requests.setReservation( data.reservation || null, {
            transaction,
        });
        
        await service_requests.setRequested_by( isCustomerUser(currentUser) ? currentUser.id : data.requested_by || null, {
            transaction,
        });
        
        await service_requests.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        
        await service_requests.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await service_requests.setDocuments(data.documents || [], {
            transaction,
        });
        
        await service_requests.setComments(data.comments || [], {
            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,
                
                request_type: item.request_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                priority: item.priority
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                details: item.details
            ||
            null
            ,
            
                estimated_cost: item.estimated_cost
            ||
            null
            ,
            
                actual_cost: item.actual_cost
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
            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 service_requests = await db.service_requests.findOne({
            where: mergeWhereWithScope({ id }, isCustomerUser(currentUser) ? { requested_byId: currentUser.id } : null),
            transaction,
        });


        

        const updatePayload = {};
        
        if (data.request_type !== undefined) updatePayload.request_type = data.request_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.details !== undefined) updatePayload.details = data.details;
        
        
        if (data.estimated_cost !== undefined) updatePayload.estimated_cost = data.estimated_cost;
        
        
        if (data.actual_cost !== undefined) updatePayload.actual_cost = data.actual_cost;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await service_requests.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.reservation !== undefined) {
            await service_requests.setReservation(
              
              data.reservation,
              
              { transaction }
            );
        }
        
        if (data.requested_by !== undefined) {
            await service_requests.setRequested_by(
              
              isCustomerUser(currentUser) ? currentUser.id : data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.assigned_to !== undefined) {
            await service_requests.setAssigned_to(
              
              data.assigned_to,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await service_requests.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.documents !== undefined) {
            await service_requests.setDocuments(data.documents, { transaction });
        }
        
        if (data.comments !== undefined) {
            await service_requests.setComments(data.comments, { 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: mergeWhereWithScope({
                id: {
                    [Op.in]: ids,
                },
            }, isCustomerUser(currentUser) ? { requested_byId: currentUser.id } : null),
            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.findOne({
            where: mergeWhereWithScope({ id }, isCustomerUser(currentUser) ? { requested_byId: currentUser.id } : null),
            transaction,
        });

        if (!service_requests) {
            return null;
        }

        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 currentUser = (options && options.currentUser) || null;

        const service_requests = await db.service_requests.findOne({
            where: mergeWhereWithScope(where, isCustomerUser(currentUser) ? { requested_byId: currentUser.id } : null),
            transaction,
        });

        if (!service_requests) {
            return service_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.documents_service_request = await service_requests.getDocuments_service_request({
            transaction
        });
        
        
        
        
        output.activity_comments_service_request = await service_requests.getActivity_comments_service_request({
            transaction
        });
        
        
        
        
        
        
        output.tenant = await service_requests.getTenant({
            transaction
        });
        
        
        output.reservation = await service_requests.getReservation({
            transaction
        });
        
        
        output.requested_by = await service_requests.getRequested_by({
            transaction
        });
        
        
        output.assigned_to = await service_requests.getAssigned_to({
            transaction
        });
        
        
        output.documents = await service_requests.getDocuments({
            transaction
        });
        
        
        output.comments = await service_requests.getComments({
            transaction
        });
        
        
        output.organizations = await service_requests.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;
        const customerScope = isCustomerUser(user) ? { requested_byId: user.id } : null;
        

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

        if (customerScope) {
            where.requested_byId = user.id;
        }

        offset = currentPage * limit;


    let include = [

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

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

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

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

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


      {
        model: db.documents,
        as: 'documents',
        required: false,
      },

      {
        model: db.activity_comments,
        as: 'comments',
        required: false,
      },


    ];

        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.details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'service_requests',
                        'details',
                        filter.details,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'service_requests',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

      

      

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

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


      if (filter.documents) {
        const searchTerms = filter.documents.split('|');

        include = [
          {
            model: db.documents,
            as: 'documents_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  file_name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.comments) {
        const searchTerms = filter.comments.split('|');

        include = [
          {
            model: db.activity_comments,
            as: 'comments_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  body: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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, currentUser) {
        let where = {};

        if (isCustomerUser(currentUser)) {
            where.requested_byId = currentUser.id;
        }
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.and]: [
                    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,
        }));
    }

    
};

