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

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

        const support_tickets = await db.support_tickets.create(
            {
                id: data.id || undefined,
        
        ticket_number: data.ticket_number
        ||
        null
            ,
            
        subject: data.subject
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        channel: data.channel
        ||
        null
            ,
            
        priority: data.priority
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        first_response_due_at: data.first_response_due_at
        ||
        null
            ,
            
        resolution_due_at: data.resolution_due_at
        ||
        null
            ,
            
        first_response_at: data.first_response_at
        ||
        null
            ,
            
        resolved_at: data.resolved_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
        sla_breached: data.sla_breached
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await support_tickets.setTenant( data.tenant || null, {
            transaction,
        });
        
        await support_tickets.setCompany( data.company || null, {
            transaction,
        });
        
        await support_tickets.setContact( data.contact || null, {
            transaction,
        });
        
        await support_tickets.setProject( data.project || null, {
            transaction,
        });
        
        await support_tickets.setContract( data.contract || null, {
            transaction,
        });
        
        await support_tickets.setService_line( data.service_line || null, {
            transaction,
        });
        
        await support_tickets.setSla( data.sla || null, {
            transaction,
        });
        
        await support_tickets.setAssignee( data.assignee || null, {
            transaction,
        });
        
        await support_tickets.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.support_tickets.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: support_tickets.id,
            },
            data.attachments,
            options,
        );
        

        return support_tickets;
    }
    

    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 support_ticketsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                ticket_number: item.ticket_number
            ||
            null
            ,
            
                subject: item.subject
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                channel: item.channel
            ||
            null
            ,
            
                priority: item.priority
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                first_response_due_at: item.first_response_due_at
            ||
            null
            ,
            
                resolution_due_at: item.resolution_due_at
            ||
            null
            ,
            
                first_response_at: item.first_response_at
            ||
            null
            ,
            
                resolved_at: item.resolved_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
                sla_breached: item.sla_breached
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < support_tickets.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.support_tickets.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: support_tickets[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return support_tickets;
    }

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


        

        const updatePayload = {};
        
        if (data.ticket_number !== undefined) updatePayload.ticket_number = data.ticket_number;
        
        
        if (data.subject !== undefined) updatePayload.subject = data.subject;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.channel !== undefined) updatePayload.channel = data.channel;
        
        
        if (data.priority !== undefined) updatePayload.priority = data.priority;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.first_response_due_at !== undefined) updatePayload.first_response_due_at = data.first_response_due_at;
        
        
        if (data.resolution_due_at !== undefined) updatePayload.resolution_due_at = data.resolution_due_at;
        
        
        if (data.first_response_at !== undefined) updatePayload.first_response_at = data.first_response_at;
        
        
        if (data.resolved_at !== undefined) updatePayload.resolved_at = data.resolved_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        if (data.sla_breached !== undefined) updatePayload.sla_breached = data.sla_breached;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await support_tickets.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.company !== undefined) {
            await support_tickets.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.contact !== undefined) {
            await support_tickets.setContact(
              
              data.contact,
              
              { transaction }
            );
        }
        
        if (data.project !== undefined) {
            await support_tickets.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.contract !== undefined) {
            await support_tickets.setContract(
              
              data.contract,
              
              { transaction }
            );
        }
        
        if (data.service_line !== undefined) {
            await support_tickets.setService_line(
              
              data.service_line,
              
              { transaction }
            );
        }
        
        if (data.sla !== undefined) {
            await support_tickets.setSla(
              
              data.sla,
              
              { transaction }
            );
        }
        
        if (data.assignee !== undefined) {
            await support_tickets.setAssignee(
              
              data.assignee,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await support_tickets.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.support_tickets.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: support_tickets.id,
            },
            data.attachments,
            options,
        );
        

        return support_tickets;
    }

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

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

        if (support_tickets.length !== ids.length) {
            const error = new Error('One or more items were not found in the current organization scope.');
            error.code = 404;
            throw error;
        }

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


        return support_tickets;
    }

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

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

        if (!support_tickets) {
            const error = new Error('Item not found in the current organization scope.');
            error.code = 404;
            throw error;
        }

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

        await support_tickets.destroy({
            transaction
        });

        return support_tickets;
    }

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

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

        if (!support_tickets) {
            return support_tickets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ticket_comments_ticket = await support_tickets.getTicket_comments_ticket({
            transaction
        });
        
        
        output.csat_surveys_ticket = await support_tickets.getCsat_surveys_ticket({
            transaction
        });
        
        
        
        
        
        
        
        output.tenant = await support_tickets.getTenant({
            transaction
        });
        
        
        output.company = await support_tickets.getCompany({
            transaction
        });
        
        
        output.contact = await support_tickets.getContact({
            transaction
        });
        
        
        output.project = await support_tickets.getProject({
            transaction
        });
        
        
        output.contract = await support_tickets.getContract({
            transaction
        });
        
        
        output.service_line = await support_tickets.getService_line({
            transaction
        });
        
        
        output.sla = await support_tickets.getSla({
            transaction
        });
        
        
        output.assignee = await support_tickets.getAssignee({
            transaction
        });
        
        
        output.attachments = await support_tickets.getAttachments({
            transaction
        });
        
        
        output.organizations = await support_tickets.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.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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              legal_name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

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

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

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



      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

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

            
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    resolved_at: {
                    ...where.resolved_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.channel) {
                where = {
                    ...where,
                channel: filter.channel,
            };
            }
            
            if (filter.priority) {
                where = {
                    ...where,
                priority: filter.priority,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.sla_breached) {
                where = {
                    ...where,
                sla_breached: filter.sla_breached,
            };
            }
            


      

      

      

      

      

      

      

      

      
      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.support_tickets.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.organizationsId = organizationId;
        }
        

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

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

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

    
};

