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

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

        const streams = await db.streams.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        is_live: data.is_live
        ||
        false
        
            ,
            
        is_adult: data.is_adult
        ||
        false
        
            ,
            
        scheduled_start_at: data.scheduled_start_at
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        ended_at: data.ended_at
        ||
        null
            ,
            
        viewer_count: data.viewer_count
        ||
        null
            ,
            
        stream_key_hint: data.stream_key_hint
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await streams.setCreator( data.creator || null, {
            transaction,
        });
        
        await streams.setOverlay_profile( data.overlay_profile || null, {
            transaction,
        });
        
        await streams.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return 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 streamsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                is_live: item.is_live
            ||
            false
        
            ,
            
                is_adult: item.is_adult
            ||
            false
        
            ,
            
                scheduled_start_at: item.scheduled_start_at
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                ended_at: item.ended_at
            ||
            null
            ,
            
                viewer_count: item.viewer_count
            ||
            null
            ,
            
                stream_key_hint: item.stream_key_hint
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return streams;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.is_live !== undefined) updatePayload.is_live = data.is_live;
        
        
        if (data.is_adult !== undefined) updatePayload.is_adult = data.is_adult;
        
        
        if (data.scheduled_start_at !== undefined) updatePayload.scheduled_start_at = data.scheduled_start_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.viewer_count !== undefined) updatePayload.viewer_count = data.viewer_count;
        
        
        if (data.stream_key_hint !== undefined) updatePayload.stream_key_hint = data.stream_key_hint;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.creator !== undefined) {
            await streams.setCreator(
              
              data.creator,
              
              { transaction }
            );
        }
        
        if (data.overlay_profile !== undefined) {
            await streams.setOverlay_profile(
              
              data.overlay_profile,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await streams.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return streams;
    }

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

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

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


        return streams;
    }

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

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

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

        await streams.destroy({
            transaction
        });

        return streams;
    }

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

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

        if (!streams) {
            return streams;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.creator = await streams.getCreator({
            transaction
        });
        
        
        output.thumbnail_images = await streams.getThumbnail_images({
            transaction
        });
        
        
        output.overlay_profile = await streams.getOverlay_profile({
            transaction
        });
        
        
        output.organizations = await streams.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'streams',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'streams',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.stream_key_hint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'streams',
                        'stream_key_hint',
                        filter.stream_key_hint,
                    ),
                };
            }
            

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    scheduled_start_at: {
                    ...where.scheduled_start_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.viewer_countRange) {
                const [start, end] = filter.viewer_countRange;

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

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

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

            
            if (filter.category) {
                where = {
                    ...where,
                category: filter.category,
            };
            }
            
            if (filter.is_live) {
                where = {
                    ...where,
                is_live: filter.is_live,
            };
            }
            
            if (filter.is_adult) {
                where = {
                    ...where,
                is_adult: filter.is_adult,
            };
            }
            


      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



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

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'streams',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

