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

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

        const sources = await db.sources.create(
            {
                id: data.id || undefined,
        
        source_type: data.source_type
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        source_url: data.source_url
        ||
        null
            ,
            
        ingestion_status: data.ingestion_status
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
        ingested_at: data.ingested_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sources.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await sources.setSubject( data.subject || null, {
            transaction,
        });
        
        await sources.setTopic( data.topic || null, {
            transaction,
        });
        
        await sources.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return sources;
    }
    

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

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

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

        return sources;
    }

    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 sources = await db.sources.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.source_url !== undefined) updatePayload.source_url = data.source_url;
        
        
        if (data.ingestion_status !== undefined) updatePayload.ingestion_status = data.ingestion_status;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        if (data.ingested_at !== undefined) updatePayload.ingested_at = data.ingested_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await sources.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await sources.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.topic !== undefined) {
            await sources.setTopic(
              
              data.topic,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await sources.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

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

        return sources;
    }

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

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

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


        return sources;
    }

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

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

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

        await sources.destroy({
            transaction
        });

        return sources;
    }

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

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

        if (!sources) {
            return sources;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.source_chunks_source = await sources.getSource_chunks_source({
            transaction
        });
        
        
        output.ai_jobs_source = await sources.getAi_jobs_source({
            transaction
        });
        
        
        output.concept_maps_source = await sources.getConcept_maps_source({
            transaction
        });
        
        
        output.study_guides_source = await sources.getStudy_guides_source({
            transaction
        });
        
        
        output.flashcard_decks_source = await sources.getFlashcard_decks_source({
            transaction
        });
        
        
        
        
        
        
        output.quizzes_source = await sources.getQuizzes_source({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.workspace = await sources.getWorkspace({
            transaction
        });
        
        
        output.subject = await sources.getSubject({
            transaction
        });
        
        
        output.topic = await sources.getTopic({
            transaction
        });
        
        
        output.source_file = await sources.getSource_file({
            transaction
        });
        
        
        output.organizations = await sources.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.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



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

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sources',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.source_url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sources',
                        'source_url',
                        filter.source_url,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'sources',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

        const records = await db.sources.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,
        }));
    }

    
};

