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

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

        const live_streams = await db.live_streams.create(
            {
                id: data.id || undefined,
        
        title_text: data.title_text
        ||
        null
            ,
            
        description_text: data.description_text
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        stream_key: data.stream_key
        ||
        null
            ,
            
        playback_url: data.playback_url
        ||
        null
            ,
            
        peak_viewers: data.peak_viewers
        ||
        null
            ,
            
        total_views: data.total_views
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await live_streams.setHost( data.host || null, {
            transaction,
        });
        
        await live_streams.setReplay_post( data.replay_post || null, {
            transaction,
        });
        

        

        

        return live_streams;
    }
    

    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 live_streamsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title_text: item.title_text
            ||
            null
            ,
            
                description_text: item.description_text
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                stream_key: item.stream_key
            ||
            null
            ,
            
                playback_url: item.playback_url
            ||
            null
            ,
            
                peak_viewers: item.peak_viewers
            ||
            null
            ,
            
                total_views: item.total_views
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return live_streams;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
        
        
        if (data.description_text !== undefined) updatePayload.description_text = data.description_text;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.ended_at !== undefined) updatePayload.ended_at = data.ended_at;
        
        
        if (data.stream_key !== undefined) updatePayload.stream_key = data.stream_key;
        
        
        if (data.playback_url !== undefined) updatePayload.playback_url = data.playback_url;
        
        
        if (data.peak_viewers !== undefined) updatePayload.peak_viewers = data.peak_viewers;
        
        
        if (data.total_views !== undefined) updatePayload.total_views = data.total_views;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.host !== undefined) {
            await live_streams.setHost(
              
              data.host,
              
              { transaction }
            );
        }
        
        if (data.replay_post !== undefined) {
            await live_streams.setReplay_post(
              
              data.replay_post,
              
              { transaction }
            );
        }
        

        
        

        

        return live_streams;
    }

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

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

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


        return live_streams;
    }

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

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

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

        await live_streams.destroy({
            transaction
        });

        return live_streams;
    }

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

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

        if (!live_streams) {
            return live_streams;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.content_moderation_reports_live_stream = await live_streams.getContent_moderation_reports_live_stream({
            transaction
        });
        
        
        
        
        
        output.host = await live_streams.getHost({
            transaction
        });
        
        
        output.replay_post = await live_streams.getReplay_post({
            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: 'host',
        
        where: filter.host ? {
          [Op.or]: [
            { id: { [Op.in]: filter.host.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.host.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.posts,
        as: 'replay_post',
        
        where: filter.replay_post ? {
          [Op.or]: [
            { id: { [Op.in]: filter.replay_post.split('|').map(term => Utils.uuid(term)) } },
            {
              caption: {
                [Op.or]: filter.replay_post.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.title_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'live_streams',
                        'title_text',
                        filter.title_text,
                    ),
                };
            }
            
            if (filter.description_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'live_streams',
                        'description_text',
                        filter.description_text,
                    ),
                };
            }
            
            if (filter.stream_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'live_streams',
                        'stream_key',
                        filter.stream_key,
                    ),
                };
            }
            
            if (filter.playback_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'live_streams',
                        'playback_url',
                        filter.playback_url,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      



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

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

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

    
};

