
const db = require('../models');
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,
        
        name: data.name
        ||
        null
            ,
            
        asset_type: data.asset_type
        ||
        null
            ,

        type: data.type
        ||
        'general'
            ,
            
        cdn_url: data.cdn_url
        ||
        null
            ,
            
        storage_key: data.storage_key
        ||
        null
            ,
            
        mime_type: data.mime_type
        ||
        null
            ,
            
        size_mb: data.size_mb
        ||
        null
            ,
            
        width_px: data.width_px
        ||
        null
            ,
            
        height_px: data.height_px
        ||
        null
            ,
            
        duration_sec: data.duration_sec
        ||
        null
            ,
            
        checksum: data.checksum
        ||
        null
            ,
            
        is_public: data.is_public
        ||
        false
        
            ,
            
        is_deleted: data.is_deleted
        ||
        false
        
            ,
            
        deleted_at_time: data.deleted_at_time
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        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,
                
                name: item.name
            ||
            null
            ,
            
                asset_type: item.asset_type
            ||
            null
            ,

                type: item.type
            ||
            'general'
            ,
            
                cdn_url: item.cdn_url
            ||
            null
            ,
            
                storage_key: item.storage_key
            ||
            null
            ,
            
                mime_type: item.mime_type
            ||
            null
            ,
            
                size_mb: item.size_mb
            ||
            null
            ,
            
                width_px: item.width_px
            ||
            null
            ,
            
                height_px: item.height_px
            ||
            null
            ,
            
                duration_sec: item.duration_sec
            ||
            null
            ,
            
                checksum: item.checksum
            ||
            null
            ,
            
                is_public: item.is_public
            ||
            false
        
            ,
            
                is_deleted: item.is_deleted
            ||
            false
        
            ,
            
                deleted_at_time: item.deleted_at_time
            ||
            null
            ,
            
            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
        

        return assets;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.asset_type !== undefined) updatePayload.asset_type = data.asset_type;
        
        
        if (data.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.cdn_url !== undefined) updatePayload.cdn_url = data.cdn_url;
        
        
        if (data.storage_key !== undefined) updatePayload.storage_key = data.storage_key;
        
        
        if (data.mime_type !== undefined) updatePayload.mime_type = data.mime_type;
        
        
        if (data.size_mb !== undefined) updatePayload.size_mb = data.size_mb;
        
        
        if (data.width_px !== undefined) updatePayload.width_px = data.width_px;
        
        
        if (data.height_px !== undefined) updatePayload.height_px = data.height_px;
        
        
        if (data.duration_sec !== undefined) updatePayload.duration_sec = data.duration_sec;
        
        
        if (data.checksum !== undefined) updatePayload.checksum = data.checksum;
        
        
        if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
        
        
        if (data.is_deleted !== undefined) updatePayload.is_deleted = data.is_deleted;
        
        
        if (data.deleted_at_time !== undefined) updatePayload.deleted_at_time = data.deleted_at_time;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        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.asset_variants_asset = await assets.getAsset_variants_asset({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await assets.getProject({
            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;

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



    ];

        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.cdn_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'cdn_url',
                        filter.cdn_url,
                    ),
                };
            }
            
            if (filter.storage_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'storage_key',
                        filter.storage_key,
                    ),
                };
            }
            
            if (filter.mime_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'mime_type',
                        filter.mime_type,
                    ),
                };
            }
            
            if (filter.checksum) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'assets',
                        'checksum',
                        filter.checksum,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    height_px: {
                    ...where.height_px,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.deleted_at_timeRange) {
                const [start, end] = filter.deleted_at_timeRange;

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

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


      



            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.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, ) {
        let where = {};
        
        

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

    
};
