
const db = require('../models');
const Utils = require('../utils');



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

module.exports = class Presigned_url_requestsDBApi {
    

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

        const presigned_url_requests = await db.presigned_url_requests.create(
            {
                id: data.id || undefined,
        
        purpose: data.purpose
        ||
        null
            ,
            
        asset_type: data.asset_type
        ||
        null
            ,
            
        requested_key: data.requested_key
        ||
        null
            ,
            
        mime_type: data.mime_type
        ||
        null
            ,
            
        requested_size_mb: data.requested_size_mb
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await presigned_url_requests.setProject( data.project || null, {
            transaction,
        });
        
        await presigned_url_requests.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return presigned_url_requests;
    }
    

    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 presigned_url_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                purpose: item.purpose
            ||
            null
            ,
            
                asset_type: item.asset_type
            ||
            null
            ,
            
                requested_key: item.requested_key
            ||
            null
            ,
            
                mime_type: item.mime_type
            ||
            null
            ,
            
                requested_size_mb: item.requested_size_mb
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return presigned_url_requests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.purpose !== undefined) updatePayload.purpose = data.purpose;
        
        
        if (data.asset_type !== undefined) updatePayload.asset_type = data.asset_type;
        
        
        if (data.requested_key !== undefined) updatePayload.requested_key = data.requested_key;
        
        
        if (data.mime_type !== undefined) updatePayload.mime_type = data.mime_type;
        
        
        if (data.requested_size_mb !== undefined) updatePayload.requested_size_mb = data.requested_size_mb;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return presigned_url_requests;
    }

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

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

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


        return presigned_url_requests;
    }

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

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

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

        await presigned_url_requests.destroy({
            transaction
        });

        return presigned_url_requests;
    }

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

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

        if (!presigned_url_requests) {
            return presigned_url_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.project = await presigned_url_requests.getProject({
            transaction
        });
        
        
        output.user = await presigned_url_requests.getUser({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.requested_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'presigned_url_requests',
                        'requested_key',
                        filter.requested_key,
                    ),
                };
            }
            
            if (filter.mime_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'presigned_url_requests',
                        'mime_type',
                        filter.mime_type,
                    ),
                };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'presigned_url_requests',
                        'status',
                        filter.status,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.purpose) {
                where = {
                    ...where,
                purpose: filter.purpose,
            };
            }
            
            if (filter.asset_type) {
                where = {
                    ...where,
                asset_type: filter.asset_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.presigned_url_requests.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(
                        'presigned_url_requests',
                        'requested_key',
                        query,
                    ),
                ],
            };
        }

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

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

    
};
