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

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

        const research_queries = await db.research_queries.create(
            {
                id: data.id || undefined,
        
        query_text: data.query_text
        ||
        null
            ,
            
        jurisdiction: data.jurisdiction
        ||
        null
            ,
            
        source_scope: data.source_scope
        ||
        null
            ,
            
        searched_at: data.searched_at
        ||
        null
            ,
            
        filters_json: data.filters_json
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await research_queries.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await research_queries.setMatter( data.matter || null, {
            transaction,
        });
        

        

        

        return research_queries;
    }
    

    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_queriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                query_text: item.query_text
            ||
            null
            ,
            
                jurisdiction: item.jurisdiction
            ||
            null
            ,
            
                source_scope: item.source_scope
            ||
            null
            ,
            
                searched_at: item.searched_at
            ||
            null
            ,
            
                filters_json: item.filters_json
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return research_queries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.query_text !== undefined) updatePayload.query_text = data.query_text;
        
        
        if (data.jurisdiction !== undefined) updatePayload.jurisdiction = data.jurisdiction;
        
        
        if (data.source_scope !== undefined) updatePayload.source_scope = data.source_scope;
        
        
        if (data.searched_at !== undefined) updatePayload.searched_at = data.searched_at;
        
        
        if (data.filters_json !== undefined) updatePayload.filters_json = data.filters_json;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requested_by !== undefined) {
            await research_queries.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.matter !== undefined) {
            await research_queries.setMatter(
              
              data.matter,
              
              { transaction }
            );
        }
        

        
        

        

        return research_queries;
    }

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

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

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


        return research_queries;
    }

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

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

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

        await research_queries.destroy({
            transaction
        });

        return research_queries;
    }

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

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

        if (!research_queries) {
            return research_queries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.research_results_research_query = await research_queries.getResearch_results_research_query({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.requested_by = await research_queries.getRequested_by({
            transaction
        });
        
        
        output.matter = await research_queries.getMatter({
            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.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.matters,
        as: 'matter',
        
        where: filter.matter ? {
          [Op.or]: [
            { id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.query_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'research_queries',
                        'query_text',
                        filter.query_text,
                    ),
                };
            }
            
            if (filter.jurisdiction) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'research_queries',
                        'jurisdiction',
                        filter.jurisdiction,
                    ),
                };
            }
            
            if (filter.filters_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'research_queries',
                        'filters_json',
                        filter.filters_json,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      



            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_queries.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_queries',
                        'jurisdiction',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

