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

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

        const stories = await db.stories.create(
            {
                id: data.id || undefined,
        
        story_type: data.story_type
        ||
        null
            ,
            
        text_overlay: data.text_overlay
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        view_count: data.view_count
        ||
        null
            ,
            
        allow_replies: data.allow_replies
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.stories.getTableName(),
                belongsToColumn: 'story_images',
                belongsToId: stories.id,
            },
            data.story_images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.stories.getTableName(),
                belongsToColumn: 'story_videos',
                belongsToId: stories.id,
            },
            data.story_videos,
            options,
        );
        

        return stories;
    }
    

    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 storiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                story_type: item.story_type
            ||
            null
            ,
            
                text_overlay: item.text_overlay
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                view_count: item.view_count
            ||
            null
            ,
            
                allow_replies: item.allow_replies
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return stories;
    }

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

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


        

        const updatePayload = {};
        
        if (data.story_type !== undefined) updatePayload.story_type = data.story_type;
        
        
        if (data.text_overlay !== undefined) updatePayload.text_overlay = data.text_overlay;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.view_count !== undefined) updatePayload.view_count = data.view_count;
        
        
        if (data.allow_replies !== undefined) updatePayload.allow_replies = data.allow_replies;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.stories.getTableName(),
                belongsToColumn: 'story_images',
                belongsToId: stories.id,
            },
            data.story_images,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.stories.getTableName(),
                belongsToColumn: 'story_videos',
                belongsToId: stories.id,
            },
            data.story_videos,
            options,
        );
        

        return stories;
    }

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

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

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


        return stories;
    }

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

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

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

        await stories.destroy({
            transaction
        });

        return stories;
    }

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

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

        if (!stories) {
            return stories;
        }

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

        
        
        
        
        
        
        output.reactions_story = await stories.getReactions_story({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.author = await stories.getAuthor({
            transaction
        });
        
        
        output.story_images = await stories.getStory_images({
            transaction
        });
        
        
        output.story_videos = await stories.getStory_videos({
            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: 'story_images',
      },

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

    ];

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

            
            if (filter.text_overlay) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'stories',
                        'text_overlay',
                        filter.text_overlay,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            published_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    expires_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

            
            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.expires_atRange) {
                const [start, end] = filter.expires_atRange;

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

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


      



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

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

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

    
};

