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

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

        const resume_documents = await db.resume_documents.create(
            {
                id: data.id || undefined,
        
        document_type: data.document_type
        ||
        null
            ,
            
        document_name: data.document_name
        ||
        null
            ,
            
        extracted_text: data.extracted_text
        ||
        null
            ,
            
        uploaded_at: data.uploaded_at
        ||
        null
            ,
            
        is_deleted: data.is_deleted
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await resume_documents.setUser( data.user || null, {
            transaction,
        });
        

        

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

        return resume_documents;
    }
    

    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 resume_documentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                document_type: item.document_type
            ||
            null
            ,
            
                document_name: item.document_name
            ||
            null
            ,
            
                extracted_text: item.extracted_text
            ||
            null
            ,
            
                uploaded_at: item.uploaded_at
            ||
            null
            ,
            
                is_deleted: item.is_deleted
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return resume_documents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
        
        
        if (data.document_name !== undefined) updatePayload.document_name = data.document_name;
        
        
        if (data.extracted_text !== undefined) updatePayload.extracted_text = data.extracted_text;
        
        
        if (data.uploaded_at !== undefined) updatePayload.uploaded_at = data.uploaded_at;
        
        
        if (data.is_deleted !== undefined) updatePayload.is_deleted = data.is_deleted;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await resume_documents.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

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

        return resume_documents;
    }

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

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

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


        return resume_documents;
    }

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

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

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

        await resume_documents.destroy({
            transaction
        });

        return resume_documents;
    }

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

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

        if (!resume_documents) {
            return resume_documents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await resume_documents.getUser({
            transaction
        });
        
        
        output.document_files = await resume_documents.getDocument_files({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.document_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'resume_documents',
                        'document_name',
                        filter.document_name,
                    ),
                };
            }
            
            if (filter.extracted_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'resume_documents',
                        'extracted_text',
                        filter.extracted_text,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



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

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

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

    
};

