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

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

        const posts = await db.posts.create(
            {
                id: data.id || undefined,
        
        post_type: data.post_type
        ||
        null
            ,
            
        caption: data.caption
        ||
        null
            ,
            
        link_url: data.link_url
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        comments_enabled: data.comments_enabled
        ||
        false
        
            ,
            
        is_pinned: data.is_pinned
        ||
        false
        
            ,
            
        is_sensitive: data.is_sensitive
        ||
        false
        
            ,
            
        location_text: data.location_text
        ||
        null
            ,
            
        language_code: data.language_code
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
        scheduled_for: data.scheduled_for
        ||
        null
            ,
            
        like_count: data.like_count
        ||
        null
            ,
            
        comment_count: data.comment_count
        ||
        null
            ,
            
        share_count: data.share_count
        ||
        null
            ,
            
        view_count: data.view_count
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await posts.setAuthor( data.author || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.posts.getTableName(),
                belongsToColumn: 'media_files',
                belongsToId: posts.id,
            },
            data.media_files,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.posts.getTableName(),
                belongsToColumn: 'media_images',
                belongsToId: posts.id,
            },
            data.media_images,
            options,
        );
        

        return posts;
    }
    

    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 postsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                post_type: item.post_type
            ||
            null
            ,
            
                caption: item.caption
            ||
            null
            ,
            
                link_url: item.link_url
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                comments_enabled: item.comments_enabled
            ||
            false
        
            ,
            
                is_pinned: item.is_pinned
            ||
            false
        
            ,
            
                is_sensitive: item.is_sensitive
            ||
            false
        
            ,
            
                location_text: item.location_text
            ||
            null
            ,
            
                language_code: item.language_code
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
                scheduled_for: item.scheduled_for
            ||
            null
            ,
            
                like_count: item.like_count
            ||
            null
            ,
            
                comment_count: item.comment_count
            ||
            null
            ,
            
                share_count: item.share_count
            ||
            null
            ,
            
                view_count: item.view_count
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return posts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.post_type !== undefined) updatePayload.post_type = data.post_type;
        
        
        if (data.caption !== undefined) updatePayload.caption = data.caption;
        
        
        if (data.link_url !== undefined) updatePayload.link_url = data.link_url;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.comments_enabled !== undefined) updatePayload.comments_enabled = data.comments_enabled;
        
        
        if (data.is_pinned !== undefined) updatePayload.is_pinned = data.is_pinned;
        
        
        if (data.is_sensitive !== undefined) updatePayload.is_sensitive = data.is_sensitive;
        
        
        if (data.location_text !== undefined) updatePayload.location_text = data.location_text;
        
        
        if (data.language_code !== undefined) updatePayload.language_code = data.language_code;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        if (data.scheduled_for !== undefined) updatePayload.scheduled_for = data.scheduled_for;
        
        
        if (data.like_count !== undefined) updatePayload.like_count = data.like_count;
        
        
        if (data.comment_count !== undefined) updatePayload.comment_count = data.comment_count;
        
        
        if (data.share_count !== undefined) updatePayload.share_count = data.share_count;
        
        
        if (data.view_count !== undefined) updatePayload.view_count = data.view_count;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.author !== undefined) {
            await posts.setAuthor(
              
              data.author,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.posts.getTableName(),
                belongsToColumn: 'media_files',
                belongsToId: posts.id,
            },
            data.media_files,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.posts.getTableName(),
                belongsToColumn: 'media_images',
                belongsToId: posts.id,
            },
            data.media_images,
            options,
        );
        

        return posts;
    }

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

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

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


        return posts;
    }

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

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

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

        await posts.destroy({
            transaction
        });

        return posts;
    }

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

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

        if (!posts) {
            return posts;
        }

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

        
        
        
        
        
        output.comments_post = await posts.getComments_post({
            transaction
        });
        
        
        output.reactions_post = await posts.getReactions_post({
            transaction
        });
        
        
        
        
        
        
        
        
        output.notifications_post = await posts.getNotifications_post({
            transaction
        });
        
        
        
        
        
        output.post_hashtags_post = await posts.getPost_hashtags_post({
            transaction
        });
        
        
        
        output.live_streams_replay_post = await posts.getLive_streams_replay_post({
            transaction
        });
        
        
        output.transactions_post = await posts.getTransactions_post({
            transaction
        });
        
        
        output.ai_recommendations_post = await posts.getAi_recommendations_post({
            transaction
        });
        
        
        output.content_moderation_reports_post = await posts.getContent_moderation_reports_post({
            transaction
        });
        
        
        
        
        
        output.author = await posts.getAuthor({
            transaction
        });
        
        
        output.media_files = await posts.getMedia_files({
            transaction
        });
        
        
        output.media_images = await posts.getMedia_images({
            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: 'author',
        
        where: filter.author ? {
          [Op.or]: [
            { id: { [Op.in]: filter.author.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.author.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

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

    ];

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

            
            if (filter.caption) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'posts',
                        'caption',
                        filter.caption,
                    ),
                };
            }
            
            if (filter.link_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'posts',
                        'link_url',
                        filter.link_url,
                    ),
                };
            }
            
            if (filter.location_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'posts',
                        'location_text',
                        filter.location_text,
                    ),
                };
            }
            
            if (filter.language_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'posts',
                        'language_code',
                        filter.language_code,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.post_type) {
                where = {
                    ...where,
                post_type: filter.post_type,
            };
            }
            
            if (filter.visibility) {
                where = {
                    ...where,
                visibility: filter.visibility,
            };
            }
            
            if (filter.comments_enabled) {
                where = {
                    ...where,
                comments_enabled: filter.comments_enabled,
            };
            }
            
            if (filter.is_pinned) {
                where = {
                    ...where,
                is_pinned: filter.is_pinned,
            };
            }
            
            if (filter.is_sensitive) {
                where = {
                    ...where,
                is_sensitive: filter.is_sensitive,
            };
            }
            


      



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

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

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

    
};

