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

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

        const facta_queries = await db.facta_queries.create(
            {
                id: data.id || undefined,
        
        query_text: data.query_text
        ||
        null
            ,
            
        mode: data.mode
        ||
        null
            ,
            
        sensitivity: data.sensitivity
        ||
        null
            ,
            
        queried_at: data.queried_at
        ||
        null
            ,
            
        is_history_saved: data.is_history_saved
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await facta_queries.setUser( data.user || null, {
            transaction,
        });
        
        await facta_queries.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return facta_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 facta_queriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                query_text: item.query_text
            ||
            null
            ,
            
                mode: item.mode
            ||
            null
            ,
            
                sensitivity: item.sensitivity
            ||
            null
            ,
            
                queried_at: item.queried_at
            ||
            null
            ,
            
                is_history_saved: item.is_history_saved
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return facta_queries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.query_text !== undefined) updatePayload.query_text = data.query_text;
        
        
        if (data.mode !== undefined) updatePayload.mode = data.mode;
        
        
        if (data.sensitivity !== undefined) updatePayload.sensitivity = data.sensitivity;
        
        
        if (data.queried_at !== undefined) updatePayload.queried_at = data.queried_at;
        
        
        if (data.is_history_saved !== undefined) updatePayload.is_history_saved = data.is_history_saved;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await facta_queries.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await facta_queries.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return facta_queries;
    }

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

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

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


        return facta_queries;
    }

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

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

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

        await facta_queries.destroy({
            transaction
        });

        return facta_queries;
    }

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

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

        if (!facta_queries) {
            return facta_queries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.facta_answers_facta_query = await facta_queries.getFacta_answers_facta_query({
            transaction
        });
        
        
        
        
        
        
        output.user = await facta_queries.getUser({
            transaction
        });
        
        
        output.organizations = await facta_queries.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

            
            if (filter.mode) {
                where = {
                    ...where,
                mode: filter.mode,
            };
            }
            
            if (filter.sensitivity) {
                where = {
                    ...where,
                sensitivity: filter.sensitivity,
            };
            }
            
            if (filter.is_history_saved) {
                where = {
                    ...where,
                is_history_saved: filter.is_history_saved,
            };
            }
            


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.facta_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'facta_queries',
                        'query_text',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

