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

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

        const groups = await db.groups.create(
            {
                id: data.id || undefined,
        
        name_text: data.name_text
        ||
        null
            ,
            
        description_text: data.description_text
        ||
        null
            ,
            
        privacy_level: data.privacy_level
        ||
        null
            ,
            
        membership_approval: data.membership_approval
        ||
        null
            ,
            
        is_verified: data.is_verified
        ||
        false
        
            ,
            
        member_count: data.member_count
        ||
        null
            ,
            
        rules_text: data.rules_text
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await groups.setOwner( data.owner || null, {
            transaction,
        });
        

        
        await groups.setMembers(data.members || [], {
            transaction,
        });
        

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

        return groups;
    }
    

    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 groupsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name_text: item.name_text
            ||
            null
            ,
            
                description_text: item.description_text
            ||
            null
            ,
            
                privacy_level: item.privacy_level
            ||
            null
            ,
            
                membership_approval: item.membership_approval
            ||
            null
            ,
            
                is_verified: item.is_verified
            ||
            false
        
            ,
            
                member_count: item.member_count
            ||
            null
            ,
            
                rules_text: item.rules_text
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return groups;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name_text !== undefined) updatePayload.name_text = data.name_text;
        
        
        if (data.description_text !== undefined) updatePayload.description_text = data.description_text;
        
        
        if (data.privacy_level !== undefined) updatePayload.privacy_level = data.privacy_level;
        
        
        if (data.membership_approval !== undefined) updatePayload.membership_approval = data.membership_approval;
        
        
        if (data.is_verified !== undefined) updatePayload.is_verified = data.is_verified;
        
        
        if (data.member_count !== undefined) updatePayload.member_count = data.member_count;
        
        
        if (data.rules_text !== undefined) updatePayload.rules_text = data.rules_text;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner !== undefined) {
            await groups.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        

        
        
        if (data.members !== undefined) {
            await groups.setMembers(data.members, { transaction });
        }
        

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

        return groups;
    }

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

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

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


        return groups;
    }

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

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

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

        await groups.destroy({
            transaction
        });

        return groups;
    }

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

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

        if (!groups) {
            return groups;
        }

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

        
        
        
        
        
        
        
        
        output.conversations_group = await groups.getConversations_group({
            transaction
        });
        
        
        
        
        output.events_group = await groups.getEvents_group({
            transaction
        });
        
        
        
        output.notifications_group = await groups.getNotifications_group({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.ai_recommendations_group = await groups.getAi_recommendations_group({
            transaction
        });
        
        
        
        
        
        
        output.owner = await groups.getOwner({
            transaction
        });
        
        
        output.cover_images = await groups.getCover_images({
            transaction
        });
        
        
        output.icon_images = await groups.getIcon_images({
            transaction
        });
        
        
        output.members = await groups.getMembers({
            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: 'owner',
        
        where: filter.owner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },


      {
        model: db.users,
        as: 'members',
        required: false,
      },


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

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

    ];

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

            
            if (filter.name_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'groups',
                        'name_text',
                        filter.name_text,
                    ),
                };
            }
            
            if (filter.description_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'groups',
                        'description_text',
                        filter.description_text,
                    ),
                };
            }
            
            if (filter.rules_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'groups',
                        'rules_text',
                        filter.rules_text,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.privacy_level) {
                where = {
                    ...where,
                privacy_level: filter.privacy_level,
            };
            }
            
            if (filter.membership_approval) {
                where = {
                    ...where,
                membership_approval: filter.membership_approval,
            };
            }
            
            if (filter.is_verified) {
                where = {
                    ...where,
                is_verified: filter.is_verified,
            };
            }
            


      


      if (filter.members) {
        const searchTerms = filter.members.split('|');

        include = [
          {
            model: db.users,
            as: 'members_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  firstName: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

