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

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

        const spaces = await db.spaces.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        name_bn: data.name_bn
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        space_kind: data.space_kind
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        unread_seed_count: data.unread_seed_count
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await spaces.setCategory( data.category || null, {
            transaction,
        });
        

        

        

        return 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 spacesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                name_bn: item.name_bn
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                space_kind: item.space_kind
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                unread_seed_count: item.unread_seed_count
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return spaces;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.name_bn !== undefined) updatePayload.name_bn = data.name_bn;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.space_kind !== undefined) updatePayload.space_kind = data.space_kind;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.unread_seed_count !== undefined) updatePayload.unread_seed_count = data.unread_seed_count;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.category !== undefined) {
            await spaces.setCategory(
              
              data.category,
              
              { transaction }
            );
        }
        

        
        

        

        return spaces;
    }

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

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

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


        return spaces;
    }

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

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

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

        await spaces.destroy({
            transaction
        });

        return spaces;
    }

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

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

        if (!spaces) {
            return spaces;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.space_memberships_space = await spaces.getSpace_memberships_space({
            transaction
        });
        
        
        output.community_posts_space = await spaces.getCommunity_posts_space({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.live_events_space = await spaces.getLive_events_space({
            transaction
        });
        
        
        
        
        
        output.category = await spaces.getCategory({
            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.subject_categories,
        as: 'category',
        
        where: filter.category ? {
          [Op.or]: [
            { id: { [Op.in]: filter.category.split('|').map(term => Utils.uuid(term)) } },
            {
              name_en: {
                [Op.or]: filter.category.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    unread_seed_count: {
                    ...where.unread_seed_count,
                            [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.space_kind) {
                where = {
                    ...where,
                space_kind: filter.space_kind,
            };
            }
            


      



            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.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'spaces',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

