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

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

        const pdf_reports = await db.pdf_reports.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        report_type: data.report_type
        ||
        null
            ,
            
        period_start_at: data.period_start_at
        ||
        null
            ,
            
        period_end_at: data.period_end_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await pdf_reports.setTrading_account( data.trading_account || null, {
            transaction,
        });
        

        

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

        return pdf_reports;
    }
    

    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 pdf_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                report_type: item.report_type
            ||
            null
            ,
            
                period_start_at: item.period_start_at
            ||
            null
            ,
            
                period_end_at: item.period_end_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return pdf_reports;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.report_type !== undefined) updatePayload.report_type = data.report_type;
        
        
        if (data.period_start_at !== undefined) updatePayload.period_start_at = data.period_start_at;
        
        
        if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trading_account !== undefined) {
            await pdf_reports.setTrading_account(
              
              data.trading_account,
              
              { transaction }
            );
        }
        

        
        

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

        return pdf_reports;
    }

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

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

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


        return pdf_reports;
    }

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

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

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

        await pdf_reports.destroy({
            transaction
        });

        return pdf_reports;
    }

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

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

        if (!pdf_reports) {
            return pdf_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.trading_account = await pdf_reports.getTrading_account({
            transaction
        });
        
        
        output.report_file = await pdf_reports.getReport_file({
            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.trading_accounts,
        as: 'trading_account',
        
        where: filter.trading_account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.trading_account.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.trading_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

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

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    period_end_at: {
                    ...where.period_end_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.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.pdf_reports.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(
                        'pdf_reports',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

    
};

