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

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

        const analyst_ratings = await db.analyst_ratings.create(
            {
                id: data.id || undefined,
        
        firm_name: data.firm_name
        ||
        null
            ,
            
        rating: data.rating
        ||
        null
            ,
            
        price_target: data.price_target
        ||
        null
            ,
            
        rating_at: data.rating_at
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        source_url: data.source_url
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return analyst_ratings;
    }
    

    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 analyst_ratingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                firm_name: item.firm_name
            ||
            null
            ,
            
                rating: item.rating
            ||
            null
            ,
            
                price_target: item.price_target
            ||
            null
            ,
            
                rating_at: item.rating_at
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                source_url: item.source_url
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return analyst_ratings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.firm_name !== undefined) updatePayload.firm_name = data.firm_name;
        
        
        if (data.rating !== undefined) updatePayload.rating = data.rating;
        
        
        if (data.price_target !== undefined) updatePayload.price_target = data.price_target;
        
        
        if (data.rating_at !== undefined) updatePayload.rating_at = data.rating_at;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.source_url !== undefined) updatePayload.source_url = data.source_url;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return analyst_ratings;
    }

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

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

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


        return analyst_ratings;
    }

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

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

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

        await analyst_ratings.destroy({
            transaction
        });

        return analyst_ratings;
    }

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

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

        if (!analyst_ratings) {
            return analyst_ratings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.market_symbol = await analyst_ratings.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.firm_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'analyst_ratings',
                        'firm_name',
                        filter.firm_name,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'analyst_ratings',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.source_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'analyst_ratings',
                        'source_url',
                        filter.source_url,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.rating) {
                where = {
                    ...where,
                rating: filter.rating,
            };
            }
            


      



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

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

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

    
};

