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

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

        const export_requests = await db.export_requests.create(
            {
                id: data.id || undefined,
        
        exportType: data.exportType
        ||
        null
            ,
            
        filtersJson: data.filtersJson
        ||
        null
            ,
            
        recordCount: data.recordCount
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        approvedAt: data.approvedAt
        ||
        null
            ,
            
        expiresAt: data.expiresAt
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await export_requests.setRequestedByUser( data.requestedByUser || null, {
            transaction,
        });
        
        await export_requests.setApprovedByUser( data.approvedByUser || null, {
            transaction,
        });
        

        

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

        return export_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 export_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                exportType: item.exportType
            ||
            null
            ,
            
                filtersJson: item.filtersJson
            ||
            null
            ,
            
                recordCount: item.recordCount
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                approvedAt: item.approvedAt
            ||
            null
            ,
            
                expiresAt: item.expiresAt
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return export_requests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.exportType !== undefined) updatePayload.exportType = data.exportType;
        
        
        if (data.filtersJson !== undefined) updatePayload.filtersJson = data.filtersJson;
        
        
        if (data.recordCount !== undefined) updatePayload.recordCount = data.recordCount;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.approvedAt !== undefined) updatePayload.approvedAt = data.approvedAt;
        
        
        if (data.expiresAt !== undefined) updatePayload.expiresAt = data.expiresAt;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requestedByUser !== undefined) {
            await export_requests.setRequestedByUser(
              
              data.requestedByUser,
              
              { transaction }
            );
        }
        
        if (data.approvedByUser !== undefined) {
            await export_requests.setApprovedByUser(
              
              data.approvedByUser,
              
              { transaction }
            );
        }
        

        
        

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

        return export_requests;
    }

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

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

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


        return export_requests;
    }

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

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

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

        await export_requests.destroy({
            transaction
        });

        return export_requests;
    }

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

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

        if (!export_requests) {
            return export_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.requestedByUser = await export_requests.getRequestedByUser({
            transaction
        });
        
        
        output.approvedByUser = await export_requests.getApprovedByUser({
            transaction
        });
        
        
        output.fileUrl = await export_requests.getFileUrl({
            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: 'requestedByUser',
        
        where: filter.requestedByUser ? {
          [Op.or]: [
            { id: { [Op.in]: filter.requestedByUser.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.requestedByUser.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.exportType) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'export_requests',
                        'exportType',
                        filter.exportType,
                    ),
                };
            }
            
            if (filter.filtersJson) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'export_requests',
                        'filtersJson',
                        filter.filtersJson,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    expiresAt: {
                    ...where.expiresAt,
                            [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.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.export_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(
                        'export_requests',
                        'exportType',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

