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

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

        const report_exports = await db.report_exports.create(
            {
                id: data.id || undefined,
        
        report_type: data.report_type
        ||
        null
            ,
            
        format: data.format
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await report_exports.setCompany( data.company || null, {
            transaction,
        });
        
        await report_exports.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await report_exports.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return report_exports;
    }
    

    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 report_exportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                report_type: item.report_type
            ||
            null
            ,
            
                format: item.format
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                generated_at: item.generated_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 report_exports = await db.report_exports.bulkCreate(report_exportsData, { transaction });

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

        return report_exports;
    }

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


        

        const updatePayload = {};
        
        if (data.report_type !== undefined) updatePayload.report_type = data.report_type;
        
        
        if (data.format !== undefined) updatePayload.format = data.format;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await report_exports.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.requested_by !== undefined) {
            await report_exports.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await report_exports.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return report_exports;
    }

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

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

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


        return report_exports;
    }

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

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

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

        await report_exports.destroy({
            transaction
        });

        return report_exports;
    }

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

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

        if (!report_exports) {
            return report_exports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await report_exports.getCompany({
            transaction
        });
        
        
        output.requested_by = await report_exports.getRequested_by({
            transaction
        });
        
        
        output.report_file = await report_exports.getReport_file({
            transaction
        });
        
        
        output.organizations = await report_exports.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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              company_name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            

            
            

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

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

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

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

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

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

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


      

      

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

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

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

    
};

