
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,
        
        media_type: data.media_type
        ||
        null
            ,
            
        caption: data.caption
        ||
        null
            ,
            
        close_friends_only: data.close_friends_only
        ||
        false
        
            ,
            
        posted_at: data.posted_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
            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: 'image',
                belongsToId: stories.id,
            },
            data.image,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.stories.getTableName(),
                belongsToColumn: 'video',
                belongsToId: stories.id,
            },
            data.video,
            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,
                
                media_type: item.media_type
            ||
            null
            ,
            
                caption: item.caption
            ||
            null
            ,
            
                close_friends_only: item.close_friends_only
            ||
            false
        
            ,
            
                posted_at: item.posted_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
            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: 'image',
                    belongsToId: stories[i].id,
                },
                data[i].image,
                options,
            );
        }
        
        for (let i = 0; i < stories.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.stories.getTableName(),
                    belongsToColumn: 'video',
                    belongsToId: stories[i].id,
                },
                data[i].video,
                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.media_type !== undefined) updatePayload.media_type = data.media_type;
        
        
        if (data.caption !== undefined) updatePayload.caption = data.caption;
        
        
        if (data.close_friends_only !== undefined) updatePayload.close_friends_only = data.close_friends_only;
        
        
        if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        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: 'image',
                belongsToId: stories.id,
            },
            data.image,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.stories.getTableName(),
                belongsToColumn: 'video',
                belongsToId: stories.id,
            },
            data.video,
            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.story_views_story = await stories.getStory_views_story({
            transaction
        });
        
        
        
        output.highlight_items_story = await stories.getHighlight_items_story({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.author = await stories.getAuthor({
            transaction
        });
        
        
        output.image = await stories.getImage({
            transaction
        });
        
        
        output.video = await stories.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: 'image',
      },

      {
        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(
                        'stories',
                        'caption',
                        filter.caption,
                    ),
                };
            }
            

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    posted_at: {
                    ...where.posted_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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      



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

        const records = await db.stories.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,
        }));
    }

    
};

