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

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

        const confirmations = await db.confirmations.create(
            {
                id: data.id || undefined,
        
        state: data.state
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        risk_notes: data.risk_notes
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        responded_at: data.responded_at
        ||
        null
            ,
            
        user_response: data.user_response
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await confirmations.setTask( data.task || null, {
            transaction,
        });
        
        await confirmations.setTool_run( data.tool_run || null, {
            transaction,
        });
        
        await confirmations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return confirmations;
    }
    

    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 confirmationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                state: item.state
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                risk_notes: item.risk_notes
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                responded_at: item.responded_at
            ||
            null
            ,
            
                user_response: item.user_response
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return confirmations;
    }

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


        

        const updatePayload = {};
        
        if (data.state !== undefined) updatePayload.state = data.state;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.risk_notes !== undefined) updatePayload.risk_notes = data.risk_notes;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.responded_at !== undefined) updatePayload.responded_at = data.responded_at;
        
        
        if (data.user_response !== undefined) updatePayload.user_response = data.user_response;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.task !== undefined) {
            await confirmations.setTask(
              
              data.task,
              
              { transaction }
            );
        }
        
        if (data.tool_run !== undefined) {
            await confirmations.setTool_run(
              
              data.tool_run,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await confirmations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return confirmations;
    }

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

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

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


        return confirmations;
    }

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

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

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

        await confirmations.destroy({
            transaction
        });

        return confirmations;
    }

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

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

        if (!confirmations) {
            return confirmations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.task = await confirmations.getTask({
            transaction
        });
        
        
        output.tool_run = await confirmations.getTool_run({
            transaction
        });
        
        
        output.organizations = await confirmations.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.tasks,
        as: 'task',
        
        where: filter.task ? {
          [Op.or]: [
            { id: { [Op.in]: filter.task.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.task.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

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

            
            

            
            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.responded_atRange) {
                const [start, end] = filter.responded_atRange;

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

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

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

            
            if (filter.state) {
                where = {
                    ...where,
                state: filter.state,
            };
            }
            


      

      

      
      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.confirmations.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(
                        'confirmations',
                        'state',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

