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

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

        const assets = await db.assets.create(
            {
                id: data.id || undefined,
        
        asset_type: data.asset_type
        ||
        null
            ,
            
        audio_role: data.audio_role
        ||
        null
            ,
            
        name: data.name
        ||
        null
            ,
            
        duration_seconds: data.duration_seconds
        ||
        null
            ,
            
        sample_rate_hz: data.sample_rate_hz
        ||
        null
            ,
            
        bit_depth: data.bit_depth
        ||
        null
            ,
            
        is_stereo: data.is_stereo
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await assets.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await assets.setUploaded_user( data.uploaded_user || null, {
            transaction,
        });
        
        await assets.setProject( data.project || null, {
            transaction,
        });
        
        await assets.setSong( data.song || null, {
            transaction,
        });
        
        await assets.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return assets;
    }
    

    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 assetsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                asset_type: item.asset_type
            ||
            null
            ,
            
                audio_role: item.audio_role
            ||
            null
            ,
            
                name: item.name
            ||
            null
            ,
            
                duration_seconds: item.duration_seconds
            ||
            null
            ,
            
                sample_rate_hz: item.sample_rate_hz
            ||
            null
            ,
            
                bit_depth: item.bit_depth
            ||
            null
            ,
            
                is_stereo: item.is_stereo
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return assets;
    }

    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 assets = await db.assets.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.asset_type !== undefined) updatePayload.asset_type = data.asset_type;
        
        
        if (data.audio_role !== undefined) updatePayload.audio_role = data.audio_role;
        
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
        
        
        if (data.sample_rate_hz !== undefined) updatePayload.sample_rate_hz = data.sample_rate_hz;
        
        
        if (data.bit_depth !== undefined) updatePayload.bit_depth = data.bit_depth;
        
        
        if (data.is_stereo !== undefined) updatePayload.is_stereo = data.is_stereo;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await assets.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.uploaded_user !== undefined) {
            await assets.setUploaded_user(
              
              data.uploaded_user,
              
              { transaction }
            );
        }
        
        if (data.project !== undefined) {
            await assets.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.song !== undefined) {
            await assets.setSong(
              
              data.song,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await assets.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return assets;
    }

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

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

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


        return assets;
    }

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

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

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

        await assets.destroy({
            transaction
        });

        return assets;
    }

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

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

        if (!assets) {
            return assets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tracks_source_asset = await assets.getTracks_source_asset({
            transaction
        });
        
        
        
        output.generation_requests_input_asset = await assets.getGeneration_requests_input_asset({
            transaction
        });
        
        output.generation_requests_output_asset = await assets.getGeneration_requests_output_asset({
            transaction
        });
        
        
        
        
        output.mix_sessions_result_mix_asset = await assets.getMix_sessions_result_mix_asset({
            transaction
        });
        
        
        output.mastering_sessions_input_mix_asset = await assets.getMastering_sessions_input_mix_asset({
            transaction
        });
        
        output.mastering_sessions_result_master_asset = await assets.getMastering_sessions_result_master_asset({
            transaction
        });
        
        
        output.exports_export_asset = await assets.getExports_export_asset({
            transaction
        });
        
        
        
        output.marketplace_listings_preview_asset = await assets.getMarketplace_listings_preview_asset({
            transaction
        });
        
        output.marketplace_listings_deliverable_asset = await assets.getMarketplace_listings_deliverable_asset({
            transaction
        });
        
        
        
        
        output.workspace = await assets.getWorkspace({
            transaction
        });
        
        
        output.uploaded_user = await assets.getUploaded_user({
            transaction
        });
        
        
        output.project = await assets.getProject({
            transaction
        });
        
        
        output.song = await assets.getSong({
            transaction
        });
        
        
        output.file_blobs = await assets.getFile_blobs({
            transaction
        });
        
        
        output.image_blobs = await assets.getImage_blobs({
            transaction
        });
        
        
        output.organizations = await assets.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.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

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

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'name',
                        filter.name,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.asset_type) {
                where = {
                    ...where,
                asset_type: filter.asset_type,
            };
            }
            
            if (filter.audio_role) {
                where = {
                    ...where,
                audio_role: filter.audio_role,
            };
            }
            
            if (filter.is_stereo) {
                where = {
                    ...where,
                is_stereo: filter.is_stereo,
            };
            }
            


      

      

      

      

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

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

    
};

