
const db = require('../models');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Project_membershipsDBApi {
    

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

        const project_memberships = await db.project_memberships.create(
            {
                id: data.id || undefined,
        
        access_level: data.access_level
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        invited_at: data.invited_at
        ||
        null
            ,
            
        accepted_at: data.accepted_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await project_memberships.setProject( data.project || null, {
            transaction,
        });
        
        await project_memberships.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return project_memberships;
    }
    

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

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

        // For each item created, replace relation files
        

        return project_memberships;
    }

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

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


        

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

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

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

        
        

        

        return project_memberships;
    }

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

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

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


        return project_memberships;
    }

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

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

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

        await project_memberships.destroy({
            transaction
        });

        return project_memberships;
    }

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

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

        if (!project_memberships) {
            return project_memberships;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await project_memberships.getProject({
            transaction
        });
        
        
        output.user = await project_memberships.getUser({
            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;

    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: '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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        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.access_level) {
                where = {
                    ...where,
                access_level: filter.access_level,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

      



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

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

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

    
};
