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

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

        const participant_invitations = await db.participant_invitations.create(
            {
                id: data.id || undefined,
        
        invite_token: data.invite_token
        ||
        null
            ,
            
        sent_at: data.sent_at
        ||
        null
            ,
            
        viewed_at: data.viewed_at
        ||
        null
            ,
            
        accepted_at: data.accepted_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        send_count: data.send_count
        ||
        null
            ,
            
        channel: data.channel
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await participant_invitations.setContract_participant( data.contract_participant || null, {
            transaction,
        });
        
        await participant_invitations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return participant_invitations;
    }
    

    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 participant_invitationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                invite_token: item.invite_token
            ||
            null
            ,
            
                sent_at: item.sent_at
            ||
            null
            ,
            
                viewed_at: item.viewed_at
            ||
            null
            ,
            
                accepted_at: item.accepted_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                send_count: item.send_count
            ||
            null
            ,
            
                channel: item.channel
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return participant_invitations;
    }

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


        

        const updatePayload = {};
        
        if (data.invite_token !== undefined) updatePayload.invite_token = data.invite_token;
        
        
        if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
        
        
        if (data.viewed_at !== undefined) updatePayload.viewed_at = data.viewed_at;
        
        
        if (data.accepted_at !== undefined) updatePayload.accepted_at = data.accepted_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.send_count !== undefined) updatePayload.send_count = data.send_count;
        
        
        if (data.channel !== undefined) updatePayload.channel = data.channel;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.contract_participant !== undefined) {
            await participant_invitations.setContract_participant(
              
              data.contract_participant,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await participant_invitations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return participant_invitations;
    }

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

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

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


        return participant_invitations;
    }

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

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

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

        await participant_invitations.destroy({
            transaction
        });

        return participant_invitations;
    }

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

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

        if (!participant_invitations) {
            return participant_invitations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.contract_participant = await participant_invitations.getContract_participant({
            transaction
        });
        
        
        output.organizations = await participant_invitations.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_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.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    send_count: {
                    ...where.send_count,
                            [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.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.participant_invitations.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(
                        'participant_invitations',
                        'invite_token',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

