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

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

        const facta_answers = await db.facta_answers.create(
            {
                id: data.id || undefined,
        
        executive_summary: data.executive_summary
        ||
        null
            ,
            
        truth_score_percent: data.truth_score_percent
        ||
        null
            ,
            
        verification_status: data.verification_status
        ||
        null
            ,
            
        ready_to_cite_text: data.ready_to_cite_text
        ||
        null
            ,
            
        neutral_perspective: data.neutral_perspective
        ||
        null
            ,
            
        pro_perspective: data.pro_perspective
        ||
        null
            ,
            
        contra_perspective: data.contra_perspective
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await facta_answers.setFacta_query( data.facta_query || null, {
            transaction,
        });
        
        await facta_answers.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await facta_answers.setCitations(data.citations || [], {
            transaction,
        });
        

        

        return facta_answers;
    }
    

    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_answersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                executive_summary: item.executive_summary
            ||
            null
            ,
            
                truth_score_percent: item.truth_score_percent
            ||
            null
            ,
            
                verification_status: item.verification_status
            ||
            null
            ,
            
                ready_to_cite_text: item.ready_to_cite_text
            ||
            null
            ,
            
                neutral_perspective: item.neutral_perspective
            ||
            null
            ,
            
                pro_perspective: item.pro_perspective
            ||
            null
            ,
            
                contra_perspective: item.contra_perspective
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return facta_answers;
    }

    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_answers = await db.facta_answers.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.executive_summary !== undefined) updatePayload.executive_summary = data.executive_summary;
        
        
        if (data.truth_score_percent !== undefined) updatePayload.truth_score_percent = data.truth_score_percent;
        
        
        if (data.verification_status !== undefined) updatePayload.verification_status = data.verification_status;
        
        
        if (data.ready_to_cite_text !== undefined) updatePayload.ready_to_cite_text = data.ready_to_cite_text;
        
        
        if (data.neutral_perspective !== undefined) updatePayload.neutral_perspective = data.neutral_perspective;
        
        
        if (data.pro_perspective !== undefined) updatePayload.pro_perspective = data.pro_perspective;
        
        
        if (data.contra_perspective !== undefined) updatePayload.contra_perspective = data.contra_perspective;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.facta_query !== undefined) {
            await facta_answers.setFacta_query(
              
              data.facta_query,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await facta_answers.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        
        if (data.citations !== undefined) {
            await facta_answers.setCitations(data.citations, { transaction });
        }
        

        

        return facta_answers;
    }

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

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

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


        return facta_answers;
    }

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

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

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

        await facta_answers.destroy({
            transaction
        });

        return facta_answers;
    }

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

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

        if (!facta_answers) {
            return facta_answers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.facta_query = await facta_answers.getFacta_query({
            transaction
        });
        
        
        output.citations = await facta_answers.getCitations({
            transaction
        });
        
        
        output.organizations = await facta_answers.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.facta_queries,
        as: 'facta_query',
        
        where: filter.facta_query ? {
          [Op.or]: [
            { id: { [Op.in]: filter.facta_query.split('|').map(term => Utils.uuid(term)) } },
            {
              query_text: {
                [Op.or]: filter.facta_query.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.citations,
        as: 'citations',
        required: false,
      },


    ];

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

            
            if (filter.executive_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'facta_answers',
                        'executive_summary',
                        filter.executive_summary,
                    ),
                };
            }
            
            if (filter.ready_to_cite_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'facta_answers',
                        'ready_to_cite_text',
                        filter.ready_to_cite_text,
                    ),
                };
            }
            
            if (filter.neutral_perspective) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'facta_answers',
                        'neutral_perspective',
                        filter.neutral_perspective,
                    ),
                };
            }
            
            if (filter.pro_perspective) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'facta_answers',
                        'pro_perspective',
                        filter.pro_perspective,
                    ),
                };
            }
            
            if (filter.contra_perspective) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'facta_answers',
                        'contra_perspective',
                        filter.contra_perspective,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

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

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


      if (filter.citations) {
        const searchTerms = filter.citations.split('|');

        include = [
          {
            model: db.citations,
            as: 'citations_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  source_title: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

