
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
            ,
            
        location_name: data.location_name
        ||
        null
            ,
            
        comments_enabled: data.comments_enabled
        ||
        false
        
            ,
            
        is_archived: data.is_archived
        ||
        false
        
            ,
            
        published_at: data.published_at
        ||
        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: 'images',
                belongsToId: posts.id,
            },
            data.images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.posts.getTableName(),
                belongsToColumn: 'video',
                belongsToId: posts.id,
            },
            data.video,
            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
            ,
            
                location_name: item.location_name
            ||
            null
            ,
            
                comments_enabled: item.comments_enabled
            ||
            false
        
            ,
            
                is_archived: item.is_archived
            ||
            false
        
            ,
            
                published_at: item.published_at
            ||
            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: 'images',
                    belongsToId: posts[i].id,
                },
                data[i].images,
                options,
            );
        }
        
        for (let i = 0; i < posts.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.posts.getTableName(),
                    belongsToColumn: 'video',
                    belongsToId: posts[i].id,
                },
                data[i].video,
                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.location_name !== undefined) updatePayload.location_name = data.location_name;
        
        
        if (data.comments_enabled !== undefined) updatePayload.comments_enabled = data.comments_enabled;
        
        
        if (data.is_archived !== undefined) updatePayload.is_archived = data.is_archived;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        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: 'images',
                belongsToId: posts.id,
            },
            data.images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.posts.getTableName(),
                belongsToColumn: 'video',
                belongsToId: posts.id,
            },
            data.video,
            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.post_comments_post = await posts.getPost_comments_post({
            transaction
        });
        
        
        output.post_reactions_post = await posts.getPost_reactions_post({
            transaction
        });
        
        
        output.post_saves_post = await posts.getPost_saves_post({
            transaction
        });
        
        
        
        
        output.post_hashtags_post = await posts.getPost_hashtags_post({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.author = await posts.getAuthor({
            transaction
        });
        
        
        output.images = await posts.getImages({
            transaction
        });
        
        
        output.video = await posts.getVideo({
            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: 'images',
      },

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

    ];

        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.location_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'posts',
                        'location_name',
                        filter.location_name,
                    ),
                };
            }
            

            
            

            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.post_type) {
                where = {
                    ...where,
                post_type: filter.post_type,
            };
            }
            
            if (filter.comments_enabled) {
                where = {
                    ...where,
                comments_enabled: filter.comments_enabled,
            };
            }
            
            if (filter.is_archived) {
                where = {
                    ...where,
                is_archived: filter.is_archived,
            };
            }
            


      



            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,
        }));
    }

    
};

