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

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

        const user_uploads = await db.user_uploads.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        content_type: data.content_type
        ||
        null
            ,
            
        rejection_reason: data.rejection_reason
        ||
        null
            ,
            
        uploaded_at: data.uploaded_at
        ||
        null
            ,
            
        reviewed_at: data.reviewed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await user_uploads.setUser( data.user || null, {
            transaction,
        });
        

        

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

        return user_uploads;
    }
    

    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 user_uploadsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                content_type: item.content_type
            ||
            null
            ,
            
                rejection_reason: item.rejection_reason
            ||
            null
            ,
            
                uploaded_at: item.uploaded_at
            ||
            null
            ,
            
                reviewed_at: item.reviewed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return user_uploads;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.content_type !== undefined) updatePayload.content_type = data.content_type;
        
        
        if (data.rejection_reason !== undefined) updatePayload.rejection_reason = data.rejection_reason;
        
        
        if (data.uploaded_at !== undefined) updatePayload.uploaded_at = data.uploaded_at;
        
        
        if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await user_uploads.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

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

        return user_uploads;
    }

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

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

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


        return user_uploads;
    }

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

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

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

        await user_uploads.destroy({
            transaction
        });

        return user_uploads;
    }

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

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

        if (!user_uploads) {
            return user_uploads;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await user_uploads.getUser({
            transaction
        });
        
        
        output.file_assets = await user_uploads.getFile_assets({
            transaction
        });
        
        
        output.preview_images = await user_uploads.getPreview_images({
            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;

        const orderBy = null;

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

    let include = [

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



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

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

    ];

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

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

            
            

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

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.content_type) {
                where = {
                    ...where,
                content_type: filter.content_type,
            };
            }
            


      



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

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

    
};

