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

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

        const file_extractions = await db.file_extractions.create(
            {
                id: data.id || undefined,
        
        extraction_type: data.extraction_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        language: data.language
        ||
        null
            ,
            
        page_count: data.page_count
        ||
        null
            ,
            
        result_text: data.result_text
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        finished_at: data.finished_at
        ||
        null
            ,
            
        error_message: data.error_message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await file_extractions.setFile( data.file || null, {
            transaction,
        });
        

        

        

        return file_extractions;
    }
    

    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 file_extractionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                extraction_type: item.extraction_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                language: item.language
            ||
            null
            ,
            
                page_count: item.page_count
            ||
            null
            ,
            
                result_text: item.result_text
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                finished_at: item.finished_at
            ||
            null
            ,
            
                error_message: item.error_message
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return file_extractions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.extraction_type !== undefined) updatePayload.extraction_type = data.extraction_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.language !== undefined) updatePayload.language = data.language;
        
        
        if (data.page_count !== undefined) updatePayload.page_count = data.page_count;
        
        
        if (data.result_text !== undefined) updatePayload.result_text = data.result_text;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
        
        
        if (data.error_message !== undefined) updatePayload.error_message = data.error_message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.file !== undefined) {
            await file_extractions.setFile(
              
              data.file,
              
              { transaction }
            );
        }
        

        
        

        

        return file_extractions;
    }

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

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

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


        return file_extractions;
    }

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

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

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

        await file_extractions.destroy({
            transaction
        });

        return file_extractions;
    }

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

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

        if (!file_extractions) {
            return file_extractions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.file = await file_extractions.getFile({
            transaction
        });
        
        

        return output;
    }

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

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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



    ];

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

            
            if (filter.language) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'file_extractions',
                        'language',
                        filter.language,
                    ),
                };
            }
            
            if (filter.result_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'file_extractions',
                        'result_text',
                        filter.result_text,
                    ),
                };
            }
            
            if (filter.error_message) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'file_extractions',
                        'error_message',
                        filter.error_message,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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


      



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

        

        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.file_extractions.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, ) {
        let where = {};
        
        

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

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

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

    
};

