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

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

        const forum_spaces = await db.forum_spaces.create(
            {
                id: data.id || undefined,
        
        space_name: data.space_name
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        center_latitude: data.center_latitude
        ||
        null
            ,
            
        center_longitude: data.center_longitude
        ||
        null
            ,
            
        radius_meters: data.radius_meters
        ||
        null
            ,
            
        min_trust_score_to_post: data.min_trust_score_to_post
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await forum_spaces.setOwner( data.owner || null, {
            transaction,
        });
        
        await forum_spaces.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return forum_spaces;
    }
    

    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 forum_spacesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                space_name: item.space_name
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                center_latitude: item.center_latitude
            ||
            null
            ,
            
                center_longitude: item.center_longitude
            ||
            null
            ,
            
                radius_meters: item.radius_meters
            ||
            null
            ,
            
                min_trust_score_to_post: item.min_trust_score_to_post
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return forum_spaces;
    }

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


        

        const updatePayload = {};
        
        if (data.space_name !== undefined) updatePayload.space_name = data.space_name;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.center_latitude !== undefined) updatePayload.center_latitude = data.center_latitude;
        
        
        if (data.center_longitude !== undefined) updatePayload.center_longitude = data.center_longitude;
        
        
        if (data.radius_meters !== undefined) updatePayload.radius_meters = data.radius_meters;
        
        
        if (data.min_trust_score_to_post !== undefined) updatePayload.min_trust_score_to_post = data.min_trust_score_to_post;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return forum_spaces;
    }

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

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

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


        return forum_spaces;
    }

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

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

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

        await forum_spaces.destroy({
            transaction
        });

        return forum_spaces;
    }

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

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

        if (!forum_spaces) {
            return forum_spaces;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.forum_threads_space = await forum_spaces.getForum_threads_space({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner = await forum_spaces.getOwner({
            transaction
        });
        
        
        output.organizations = await forum_spaces.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.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.space_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'forum_spaces',
                        'space_name',
                        filter.space_name,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'forum_spaces',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

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

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

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

    
};

