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

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

        const earnings_reports = await db.earnings_reports.create(
            {
                id: data.id || undefined,
        
        period_end_at: data.period_end_at
        ||
        null
            ,
            
        reported_at: data.reported_at
        ||
        null
            ,
            
        reported_eps: data.reported_eps
        ||
        null
            ,
            
        estimated_eps: data.estimated_eps
        ||
        null
            ,
            
        surprise: data.surprise
        ||
        null
            ,
            
        surprise_percent: data.surprise_percent
        ||
        null
            ,
            
        reported_revenue: data.reported_revenue
        ||
        null
            ,
            
        estimated_revenue: data.estimated_revenue
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await earnings_reports.setMarket_symbol( data.market_symbol || null, {
            transaction,
        });
        

        

        

        return earnings_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 earnings_reportsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                period_end_at: item.period_end_at
            ||
            null
            ,
            
                reported_at: item.reported_at
            ||
            null
            ,
            
                reported_eps: item.reported_eps
            ||
            null
            ,
            
                estimated_eps: item.estimated_eps
            ||
            null
            ,
            
                surprise: item.surprise
            ||
            null
            ,
            
                surprise_percent: item.surprise_percent
            ||
            null
            ,
            
                reported_revenue: item.reported_revenue
            ||
            null
            ,
            
                estimated_revenue: item.estimated_revenue
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return earnings_reports;
    }

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

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


        

        const updatePayload = {};
        
        if (data.period_end_at !== undefined) updatePayload.period_end_at = data.period_end_at;
        
        
        if (data.reported_at !== undefined) updatePayload.reported_at = data.reported_at;
        
        
        if (data.reported_eps !== undefined) updatePayload.reported_eps = data.reported_eps;
        
        
        if (data.estimated_eps !== undefined) updatePayload.estimated_eps = data.estimated_eps;
        
        
        if (data.surprise !== undefined) updatePayload.surprise = data.surprise;
        
        
        if (data.surprise_percent !== undefined) updatePayload.surprise_percent = data.surprise_percent;
        
        
        if (data.reported_revenue !== undefined) updatePayload.reported_revenue = data.reported_revenue;
        
        
        if (data.estimated_revenue !== undefined) updatePayload.estimated_revenue = data.estimated_revenue;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.market_symbol !== undefined) {
            await earnings_reports.setMarket_symbol(
              
              data.market_symbol,
              
              { transaction }
            );
        }
        

        
        

        

        return earnings_reports;
    }

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

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

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


        return earnings_reports;
    }

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

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

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

        await earnings_reports.destroy({
            transaction
        });

        return earnings_reports;
    }

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

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

        if (!earnings_reports) {
            return earnings_reports;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.market_symbol = await earnings_reports.getMarket_symbol({
            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.market_symbols,
        as: 'market_symbol',
        
        where: filter.market_symbol ? {
          [Op.or]: [
            { id: { [Op.in]: filter.market_symbol.split('|').map(term => Utils.uuid(term)) } },
            {
              symbol: {
                [Op.or]: filter.market_symbol.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'earnings_reports',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            reported_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    period_end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

            
            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.reported_atRange) {
                const [start, end] = filter.reported_atRange;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      



            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.earnings_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(
                        'earnings_reports',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

