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

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

        const source_items = await db.source_items.create(
            {
                id: data.id || undefined,
        
        source_type: data.source_type
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        url: data.url
        ||
        null
            ,
            
        raw_text: data.raw_text
        ||
        null
            ,
            
        extracted_summary: data.extracted_summary
        ||
        null
            ,
            
        ingestion_status: data.ingestion_status
        ||
        null
            ,
            
        ingested_at: data.ingested_at
        ||
        null
            ,
            
        tags: data.tags
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await source_items.setProject( data.project || null, {
            transaction,
        });
        
        await source_items.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return source_items;
    }
    

    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 source_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                source_type: item.source_type
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                url: item.url
            ||
            null
            ,
            
                raw_text: item.raw_text
            ||
            null
            ,
            
                extracted_summary: item.extracted_summary
            ||
            null
            ,
            
                ingestion_status: item.ingestion_status
            ||
            null
            ,
            
                ingested_at: item.ingested_at
            ||
            null
            ,
            
                tags: item.tags
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return source_items;
    }

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


        

        const updatePayload = {};
        
        if (data.source_type !== undefined) updatePayload.source_type = data.source_type;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.url !== undefined) updatePayload.url = data.url;
        
        
        if (data.raw_text !== undefined) updatePayload.raw_text = data.raw_text;
        
        
        if (data.extracted_summary !== undefined) updatePayload.extracted_summary = data.extracted_summary;
        
        
        if (data.ingestion_status !== undefined) updatePayload.ingestion_status = data.ingestion_status;
        
        
        if (data.ingested_at !== undefined) updatePayload.ingested_at = data.ingested_at;
        
        
        if (data.tags !== undefined) updatePayload.tags = data.tags;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.project !== undefined) {
            await source_items.setProject(
              
              data.project,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await source_items.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return source_items;
    }

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

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

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


        return source_items;
    }

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

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

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

        await source_items.destroy({
            transaction
        });

        return source_items;
    }

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

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

        if (!source_items) {
            return source_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.node_evidence_items_source_item = await source_items.getNode_evidence_items_source_item({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.project = await source_items.getProject({
            transaction
        });
        
        
        output.attachments = await source_items.getAttachments({
            transaction
        });
        
        
        output.organizations = await source_items.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.projects,
        as: 'project',
        
        where: filter.project ? {
          [Op.or]: [
            { id: { [Op.in]: filter.project.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.project.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'source_items',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'source_items',
                        'url',
                        filter.url,
                    ),
                };
            }
            
            if (filter.raw_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'source_items',
                        'raw_text',
                        filter.raw_text,
                    ),
                };
            }
            
            if (filter.extracted_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'source_items',
                        'extracted_summary',
                        filter.extracted_summary,
                    ),
                };
            }
            
            if (filter.tags) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'source_items',
                        'tags',
                        filter.tags,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      
      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.source_items.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(
                        'source_items',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

