
const db = require('../models');
const Utils = require('../utils');
const {
  applyRuntimeEnvironment,
  applyRuntimeProjectFilter,
} = require('./runtime-context');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class TransitionsDBApi {
    

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

        const transitions = await db.transitions.create(
            {
                id: data.id || undefined,
        
        environment: data.environment
        ||
        null
            ,
            
        source_key: data.source_key
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        video_url: data.video_url
        ||
        null
            ,
            
        audio_url: data.audio_url
        ||
        null
            ,
            
        supports_reverse: data.supports_reverse
        ||
        false
        
            ,
            
        duration_sec: data.duration_sec
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await transitions.setProject( data.project || null, {
            transaction,
        });
        

        

        

        return transitions;
    }
    

    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 transitionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                environment: item.environment
            ||
            null
            ,
            
                source_key: item.source_key
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                slug: item.slug
            ||
            null
            ,
            
                video_url: item.video_url
            ||
            null
            ,
            
                audio_url: item.audio_url
            ||
            null
            ,
            
                supports_reverse: item.supports_reverse
            ||
            false
        
            ,
            
                duration_sec: item.duration_sec
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return transitions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.environment !== undefined) updatePayload.environment = data.environment;
        
        
        if (data.source_key !== undefined) updatePayload.source_key = data.source_key;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.slug !== undefined) updatePayload.slug = data.slug;
        
        
        if (data.video_url !== undefined) updatePayload.video_url = data.video_url;
        
        
        if (data.audio_url !== undefined) updatePayload.audio_url = data.audio_url;
        
        
        if (data.supports_reverse !== undefined) updatePayload.supports_reverse = data.supports_reverse;
        
        
        if (data.duration_sec !== undefined) updatePayload.duration_sec = data.duration_sec;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await transitions.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        

        
        

        

        return transitions;
    }

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

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

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


        return transitions;
    }

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

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

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

        await transitions.destroy({
            transaction
        });

        return transitions;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;
        const queryWhere = applyRuntimeEnvironment({ ...where }, options);
        const projectInclude = applyRuntimeProjectFilter(
            {
                model: db.projects,
                as: 'project',
            },
            options,
        );

        const transitions = await db.transitions.findOne(
            { where: queryWhere, include: [projectInclude], transaction },
        );

        if (!transitions) {
            return transitions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.page_links_transition = await transitions.getPage_links_transition({
            transaction
        });
        
        
        
        
        
        
        
        
        output.project = await transitions.getProject({
            transaction
        });
        
        

        return output;
    }

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

        

        

        offset = currentPage * limit;

    let include = [

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



    ];
        include[0] = applyRuntimeProjectFilter(include[0], options);

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

            
            if (filter.source_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transitions',
                        'source_key',
                        filter.source_key,
                    ),
                };
            }
            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transitions',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transitions',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.video_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transitions',
                        'video_url',
                        filter.video_url,
                    ),
                };
            }
            
            if (filter.audio_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transitions',
                        'audio_url',
                        filter.audio_url,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.environment) {
                where = {
                    ...where,
                environment: filter.environment,
            };
            }
            
            if (filter.supports_reverse) {
                where = {
                    ...where,
                supports_reverse: filter.supports_reverse,
            };
            }
            


      



            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,
                        },
                    };
                }
            }
        }
        
        where = applyRuntimeEnvironment(where, options);

        

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

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

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

    
};
