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

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

        const change_requests = await db.change_requests.create(
            {
                id: data.id || undefined,
        
        change_number: data.change_number
        ||
        null
            ,
            
        change_type: data.change_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        reason_for_change: data.reason_for_change
        ||
        null
            ,
            
        impact_assessment: data.impact_assessment
        ||
        null
            ,
            
        requires_validation: data.requires_validation
        ||
        false
        
            ,
            
        requires_regulatory_notification: data.requires_regulatory_notification
        ||
        false
        
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        closed_at: data.closed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await change_requests.setRequester( data.requester || null, {
            transaction,
        });
        
        await change_requests.setDocument( data.document || null, {
            transaction,
        });
        
        await change_requests.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        

        

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

        return change_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 change_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                change_number: item.change_number
            ||
            null
            ,
            
                change_type: item.change_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                reason_for_change: item.reason_for_change
            ||
            null
            ,
            
                impact_assessment: item.impact_assessment
            ||
            null
            ,
            
                requires_validation: item.requires_validation
            ||
            false
        
            ,
            
                requires_regulatory_notification: item.requires_regulatory_notification
            ||
            false
        
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                closed_at: item.closed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return change_requests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.change_number !== undefined) updatePayload.change_number = data.change_number;
        
        
        if (data.change_type !== undefined) updatePayload.change_type = data.change_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.reason_for_change !== undefined) updatePayload.reason_for_change = data.reason_for_change;
        
        
        if (data.impact_assessment !== undefined) updatePayload.impact_assessment = data.impact_assessment;
        
        
        if (data.requires_validation !== undefined) updatePayload.requires_validation = data.requires_validation;
        
        
        if (data.requires_regulatory_notification !== undefined) updatePayload.requires_regulatory_notification = data.requires_regulatory_notification;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.closed_at !== undefined) updatePayload.closed_at = data.closed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requester !== undefined) {
            await change_requests.setRequester(
              
              data.requester,
              
              { transaction }
            );
        }
        
        if (data.document !== undefined) {
            await change_requests.setDocument(
              
              data.document,
              
              { transaction }
            );
        }
        
        if (data.assigned_to !== undefined) {
            await change_requests.setAssigned_to(
              
              data.assigned_to,
              
              { transaction }
            );
        }
        

        
        

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

        return change_requests;
    }

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

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

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


        return change_requests;
    }

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

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

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

        await change_requests.destroy({
            transaction
        });

        return change_requests;
    }

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

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

        if (!change_requests) {
            return change_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.requester = await change_requests.getRequester({
            transaction
        });
        
        
        output.document = await change_requests.getDocument({
            transaction
        });
        
        
        output.supporting_files = await change_requests.getSupporting_files({
            transaction
        });
        
        
        output.assigned_to = await change_requests.getAssigned_to({
            transaction
        });
        
        

        return output;
    }

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

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

      {
        model: db.documents,
        as: 'document',
        
        where: filter.document ? {
          [Op.or]: [
            { id: { [Op.in]: filter.document.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.document.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.file,
        as: 'supporting_files',
      },

    ];

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

            
            if (filter.change_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'change_requests',
                        'change_number',
                        filter.change_number,
                    ),
                };
            }
            
            if (filter.reason_for_change) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'change_requests',
                        'reason_for_change',
                        filter.reason_for_change,
                    ),
                };
            }
            
            if (filter.impact_assessment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'change_requests',
                        'impact_assessment',
                        filter.impact_assessment,
                    ),
                };
            }
            

            
            

            
            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.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.change_type) {
                where = {
                    ...where,
                change_type: filter.change_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.requires_validation) {
                where = {
                    ...where,
                requires_validation: filter.requires_validation,
            };
            }
            
            if (filter.requires_regulatory_notification) {
                where = {
                    ...where,
                requires_regulatory_notification: filter.requires_regulatory_notification,
            };
            }
            


      

      

      



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

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

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

        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.change_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, ) {
        let where = {};
        
        

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

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

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

    
};

