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

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

        const project_collaborations = await db.project_collaborations.create(
            {
                id: data.id || undefined,
        
        permission_level: data.permission_level
        ||
        null
            ,
            
        invited_at: data.invited_at
        ||
        null
            ,
            
        accepted_at: data.accepted_at
        ||
        null
            ,
            
        invite_status: data.invite_status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await project_collaborations.setProject( data.project || null, {
            transaction,
        });
        
        await project_collaborations.setCollaborator_user( data.collaborator_user || null, {
            transaction,
        });
        
        await project_collaborations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return project_collaborations;
    }
    

    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 project_collaborationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                permission_level: item.permission_level
            ||
            null
            ,
            
                invited_at: item.invited_at
            ||
            null
            ,
            
                accepted_at: item.accepted_at
            ||
            null
            ,
            
                invite_status: item.invite_status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return project_collaborations;
    }

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


        

        const updatePayload = {};
        
        if (data.permission_level !== undefined) updatePayload.permission_level = data.permission_level;
        
        
        if (data.invited_at !== undefined) updatePayload.invited_at = data.invited_at;
        
        
        if (data.accepted_at !== undefined) updatePayload.accepted_at = data.accepted_at;
        
        
        if (data.invite_status !== undefined) updatePayload.invite_status = data.invite_status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await project_collaborations.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.collaborator_user !== undefined) {
            await project_collaborations.setCollaborator_user(
              
              data.collaborator_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await project_collaborations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return project_collaborations;
    }

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

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

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


        return project_collaborations;
    }

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

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

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

        await project_collaborations.destroy({
            transaction
        });

        return project_collaborations;
    }

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

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

        if (!project_collaborations) {
            return project_collaborations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await project_collaborations.getProject({
            transaction
        });
        
        
        output.collaborator_user = await project_collaborations.getCollaborator_user({
            transaction
        });
        
        
        output.organizations = await project_collaborations.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.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'collaborator_user',
        
        where: filter.collaborator_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.collaborator_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.collaborator_user.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.invited_atRange) {
                const [start, end] = filter.invited_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    invited_at: {
                    ...where.invited_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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.permission_level) {
                where = {
                    ...where,
                permission_level: filter.permission_level,
            };
            }
            
            if (filter.invite_status) {
                where = {
                    ...where,
                invite_status: filter.invite_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.project_collaborations.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(
                        'project_collaborations',
                        'invite_status',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

