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

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

        const project_audio_tracks = await db.project_audio_tracks.create(
            {
                id: data.id || undefined,
        
        environment: data.environment
        ||
        null
            ,
            
        source_key: data.source_key
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        slug: data.slug
        ||
        null
            ,
            
        url: data.url
        ||
        null
            ,
            
        loop: data.loop
        ||
        false
        
            ,
            
        volume: data.volume
        ||
        null
            ,
            
        sort_order: data.sort_order
        ||
        null
            ,
            
        is_enabled: data.is_enabled
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return project_audio_tracks;
    }
    

    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 project_audio_tracksData = 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
            ,
            
                url: item.url
            ||
            null
            ,
            
                loop: item.loop
            ||
            false
        
            ,
            
                volume: item.volume
            ||
            null
            ,
            
                sort_order: item.sort_order
            ||
            null
            ,
            
                is_enabled: item.is_enabled
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return project_audio_tracks;
    }

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

        const project_audio_tracks = await db.project_audio_tracks.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.url !== undefined) updatePayload.url = data.url;
        
        
        if (data.loop !== undefined) updatePayload.loop = data.loop;
        
        
        if (data.volume !== undefined) updatePayload.volume = data.volume;
        
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.is_enabled !== undefined) updatePayload.is_enabled = data.is_enabled;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return project_audio_tracks;
    }

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

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

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


        return project_audio_tracks;
    }

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

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

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

        await project_audio_tracks.destroy({
            transaction
        });

        return project_audio_tracks;
    }

    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 project_audio_tracks = await db.project_audio_tracks.findOne(
            { where: queryWhere, include: [projectInclude], transaction },
        );

        if (!project_audio_tracks) {
            return project_audio_tracks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await project_audio_tracks.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(
                        'project_audio_tracks',
                        'source_key',
                        filter.source_key,
                    ),
                };
            }
            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'project_audio_tracks',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.slug) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'project_audio_tracks',
                        'slug',
                        filter.slug,
                    ),
                };
            }
            
            if (filter.url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'project_audio_tracks',
                        'url',
                        filter.url,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



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

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

    
};
