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

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

        const esignature_events = await db.esignature_events.create(
            {
                id: data.id || undefined,
        
        action: data.action
        ||
        null
            ,
            
        subject_type: data.subject_type
        ||
        null
            ,
            
        subject_reference: data.subject_reference
        ||
        null
            ,
            
        signed_at: data.signed_at
        ||
        null
            ,
            
        meaning_of_signature: data.meaning_of_signature
        ||
        null
            ,
            
        authentication_method: data.authentication_method
        ||
        null
            ,
            
        ip_address: data.ip_address
        ||
        null
            ,
            
        user_agent: data.user_agent
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await esignature_events.setUser( data.user || null, {
            transaction,
        });
        

        

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

        return esignature_events;
    }
    

    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 esignature_eventsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                action: item.action
            ||
            null
            ,
            
                subject_type: item.subject_type
            ||
            null
            ,
            
                subject_reference: item.subject_reference
            ||
            null
            ,
            
                signed_at: item.signed_at
            ||
            null
            ,
            
                meaning_of_signature: item.meaning_of_signature
            ||
            null
            ,
            
                authentication_method: item.authentication_method
            ||
            null
            ,
            
                ip_address: item.ip_address
            ||
            null
            ,
            
                user_agent: item.user_agent
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return esignature_events;
    }

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

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


        

        const updatePayload = {};
        
        if (data.action !== undefined) updatePayload.action = data.action;
        
        
        if (data.subject_type !== undefined) updatePayload.subject_type = data.subject_type;
        
        
        if (data.subject_reference !== undefined) updatePayload.subject_reference = data.subject_reference;
        
        
        if (data.signed_at !== undefined) updatePayload.signed_at = data.signed_at;
        
        
        if (data.meaning_of_signature !== undefined) updatePayload.meaning_of_signature = data.meaning_of_signature;
        
        
        if (data.authentication_method !== undefined) updatePayload.authentication_method = data.authentication_method;
        
        
        if (data.ip_address !== undefined) updatePayload.ip_address = data.ip_address;
        
        
        if (data.user_agent !== undefined) updatePayload.user_agent = data.user_agent;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await esignature_events.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

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

        return esignature_events;
    }

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

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

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


        return esignature_events;
    }

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

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

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

        await esignature_events.destroy({
            transaction
        });

        return esignature_events;
    }

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

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

        if (!esignature_events) {
            return esignature_events;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await esignature_events.getUser({
            transaction
        });
        
        
        output.signature_artifacts = await esignature_events.getSignature_artifacts({
            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: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.subject_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'esignature_events',
                        'subject_reference',
                        filter.subject_reference,
                    ),
                };
            }
            
            if (filter.meaning_of_signature) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'esignature_events',
                        'meaning_of_signature',
                        filter.meaning_of_signature,
                    ),
                };
            }
            
            if (filter.authentication_method) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'esignature_events',
                        'authentication_method',
                        filter.authentication_method,
                    ),
                };
            }
            
            if (filter.ip_address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'esignature_events',
                        'ip_address',
                        filter.ip_address,
                    ),
                };
            }
            
            if (filter.user_agent) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'esignature_events',
                        'user_agent',
                        filter.user_agent,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



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

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

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

    
};

