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

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

        const signing_actions = await db.signing_actions.create(
            {
                id: data.id || undefined,
        
        revision_number: data.revision_number
        ||
        null
            ,
            
        action_type: data.action_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        action_at: data.action_at
        ||
        null
            ,
            
        signature_hash: data.signature_hash
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await signing_actions.setContract_folder( data.contract_folder || null, {
            transaction,
        });
        
        await signing_actions.setContract_participant( data.contract_participant || null, {
            transaction,
        });
        
        await signing_actions.setContract_document( data.contract_document || null, {
            transaction,
        });
        
        await signing_actions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return signing_actions;
    }
    

    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 signing_actionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                revision_number: item.revision_number
            ||
            null
            ,
            
                action_type: item.action_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                action_at: item.action_at
            ||
            null
            ,
            
                signature_hash: item.signature_hash
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return signing_actions;
    }

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


        

        const updatePayload = {};
        
        if (data.revision_number !== undefined) updatePayload.revision_number = data.revision_number;
        
        
        if (data.action_type !== undefined) updatePayload.action_type = data.action_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.action_at !== undefined) updatePayload.action_at = data.action_at;
        
        
        if (data.signature_hash !== undefined) updatePayload.signature_hash = data.signature_hash;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.contract_folder !== undefined) {
            await signing_actions.setContract_folder(
              
              data.contract_folder,
              
              { transaction }
            );
        }
        
        if (data.contract_participant !== undefined) {
            await signing_actions.setContract_participant(
              
              data.contract_participant,
              
              { transaction }
            );
        }
        
        if (data.contract_document !== undefined) {
            await signing_actions.setContract_document(
              
              data.contract_document,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await signing_actions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return signing_actions;
    }

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

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

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


        return signing_actions;
    }

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

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

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

        await signing_actions.destroy({
            transaction
        });

        return signing_actions;
    }

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

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

        if (!signing_actions) {
            return signing_actions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.revocation_requests_signing_action = await signing_actions.getRevocation_requests_signing_action({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.contract_folder = await signing_actions.getContract_folder({
            transaction
        });
        
        
        output.contract_participant = await signing_actions.getContract_participant({
            transaction
        });
        
        
        output.contract_document = await signing_actions.getContract_document({
            transaction
        });
        
        
        output.signature_evidence_file = await signing_actions.getSignature_evidence_file({
            transaction
        });
        
        
        output.organizations = await signing_actions.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.contract_folders,
        as: 'contract_folder',
        
        where: filter.contract_folder ? {
          [Op.or]: [
            { id: { [Op.in]: filter.contract_folder.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.contract_folder.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



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

    ];

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

            
            if (filter.signature_hash) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'signing_actions',
                        'signature_hash',
                        filter.signature_hash,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

      

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

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

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

    
};

