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

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

        const deep_dive_links = await db.deep_dive_links.create(
            {
                id: data.id || undefined,
        
        title_text: data.title_text
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        validation_status: data.validation_status
        ||
        null
            ,
            
        ai_confidence: data.ai_confidence
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await deep_dive_links.setCreator( data.creator || null, {
            transaction,
        });
        
        await deep_dive_links.setOrganizations( data.organizations || null, {
            transaction,
        });
        

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

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.deep_dive_links.getTableName(),
                belongsToColumn: 'evidence_files',
                belongsToId: deep_dive_links.id,
            },
            data.evidence_files,
            options,
        );
        

        return deep_dive_links;
    }
    

    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 deep_dive_linksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title_text: item.title_text
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                validation_status: item.validation_status
            ||
            null
            ,
            
                ai_confidence: item.ai_confidence
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < deep_dive_links.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.deep_dive_links.getTableName(),
                    belongsToColumn: 'evidence_files',
                    belongsToId: deep_dive_links[i].id,
                },
                data[i].evidence_files,
                options,
            );
        }
        

        return deep_dive_links;
    }

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


        

        const updatePayload = {};
        
        if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.validation_status !== undefined) updatePayload.validation_status = data.validation_status;
        
        
        if (data.ai_confidence !== undefined) updatePayload.ai_confidence = data.ai_confidence;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.creator !== undefined) {
            await deep_dive_links.setCreator(
              
              data.creator,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await deep_dive_links.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

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

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.deep_dive_links.getTableName(),
                belongsToColumn: 'evidence_files',
                belongsToId: deep_dive_links.id,
            },
            data.evidence_files,
            options,
        );
        

        return deep_dive_links;
    }

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

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

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


        return deep_dive_links;
    }

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

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

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

        await deep_dive_links.destroy({
            transaction
        });

        return deep_dive_links;
    }

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

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

        if (!deep_dive_links) {
            return deep_dive_links;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.posts_deep_dive_link = await deep_dive_links.getPosts_deep_dive_link({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.creator = await deep_dive_links.getCreator({
            transaction
        });
        
        
        output.evidence_files = await deep_dive_links.getEvidence_files({
            transaction
        });
        
        
        output.citations = await deep_dive_links.getCitations({
            transaction
        });
        
        
        output.organizations = await deep_dive_links.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: 'creator',
        
        where: filter.creator ? {
          [Op.or]: [
            { id: { [Op.in]: filter.creator.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.creator.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


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


      {
        model: db.file,
        as: 'evidence_files',
      },

    ];

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

            
            if (filter.title_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deep_dive_links',
                        'title_text',
                        filter.title_text,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'deep_dive_links',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.validation_status) {
                where = {
                    ...where,
                validation_status: filter.validation_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.deep_dive_links.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(
                        'deep_dive_links',
                        'title_text',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

