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

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

        const research_results = await db.research_results.create(
            {
                id: data.id || undefined,
        
        relevance_score: data.relevance_score
        ||
        null
            ,
            
        snippet: data.snippet
        ||
        null
            ,
            
        rule_statement: data.rule_statement
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await research_results.setResearch_query( data.research_query || null, {
            transaction,
        });
        
        await research_results.setLegal_source( data.legal_source || null, {
            transaction,
        });
        

        

        

        return research_results;
    }
    

    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 research_resultsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                relevance_score: item.relevance_score
            ||
            null
            ,
            
                snippet: item.snippet
            ||
            null
            ,
            
                rule_statement: item.rule_statement
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return research_results;
    }

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

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


        

        const updatePayload = {};
        
        if (data.relevance_score !== undefined) updatePayload.relevance_score = data.relevance_score;
        
        
        if (data.snippet !== undefined) updatePayload.snippet = data.snippet;
        
        
        if (data.rule_statement !== undefined) updatePayload.rule_statement = data.rule_statement;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.research_query !== undefined) {
            await research_results.setResearch_query(
              
              data.research_query,
              
              { transaction }
            );
        }
        
        if (data.legal_source !== undefined) {
            await research_results.setLegal_source(
              
              data.legal_source,
              
              { transaction }
            );
        }
        

        
        

        

        return research_results;
    }

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

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

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


        return research_results;
    }

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

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

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

        await research_results.destroy({
            transaction
        });

        return research_results;
    }

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

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

        if (!research_results) {
            return research_results;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.research_query = await research_results.getResearch_query({
            transaction
        });
        
        
        output.legal_source = await research_results.getLegal_source({
            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.research_queries,
        as: 'research_query',
        
        where: filter.research_query ? {
          [Op.or]: [
            { id: { [Op.in]: filter.research_query.split('|').map(term => Utils.uuid(term)) } },
            {
              jurisdiction: {
                [Op.or]: filter.research_query.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.snippet) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'research_results',
                        'snippet',
                        filter.snippet,
                    ),
                };
            }
            
            if (filter.rule_statement) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'research_results',
                        'rule_statement',
                        filter.rule_statement,
                    ),
                };
            }
            

            
            

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

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

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

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

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

    
};

