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

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

        const ai_contract_classifications = await db.ai_contract_classifications.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        model_name: data.model_name
        ||
        null
            ,
            
        confidence: data.confidence
        ||
        null
            ,
            
        predicted_category: data.predicted_category
        ||
        null
            ,
            
        predicted_document_type: data.predicted_document_type
        ||
        null
            ,
            
        is_disallowed: data.is_disallowed
        ||
        false
        
            ,
            
        disallow_reason: data.disallow_reason
        ||
        null
            ,
            
        classified_at: data.classified_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_contract_classifications.setContract_document( data.contract_document || null, {
            transaction,
        });
        
        await ai_contract_classifications.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return ai_contract_classifications;
    }
    

    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 ai_contract_classificationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                model_name: item.model_name
            ||
            null
            ,
            
                confidence: item.confidence
            ||
            null
            ,
            
                predicted_category: item.predicted_category
            ||
            null
            ,
            
                predicted_document_type: item.predicted_document_type
            ||
            null
            ,
            
                is_disallowed: item.is_disallowed
            ||
            false
        
            ,
            
                disallow_reason: item.disallow_reason
            ||
            null
            ,
            
                classified_at: item.classified_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ai_contract_classifications;
    }

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.model_name !== undefined) updatePayload.model_name = data.model_name;
        
        
        if (data.confidence !== undefined) updatePayload.confidence = data.confidence;
        
        
        if (data.predicted_category !== undefined) updatePayload.predicted_category = data.predicted_category;
        
        
        if (data.predicted_document_type !== undefined) updatePayload.predicted_document_type = data.predicted_document_type;
        
        
        if (data.is_disallowed !== undefined) updatePayload.is_disallowed = data.is_disallowed;
        
        
        if (data.disallow_reason !== undefined) updatePayload.disallow_reason = data.disallow_reason;
        
        
        if (data.classified_at !== undefined) updatePayload.classified_at = data.classified_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.contract_document !== undefined) {
            await ai_contract_classifications.setContract_document(
              
              data.contract_document,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await ai_contract_classifications.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return ai_contract_classifications;
    }

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

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

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


        return ai_contract_classifications;
    }

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

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

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

        await ai_contract_classifications.destroy({
            transaction
        });

        return ai_contract_classifications;
    }

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

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

        if (!ai_contract_classifications) {
            return ai_contract_classifications;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.contract_document = await ai_contract_classifications.getContract_document({
            transaction
        });
        
        
        output.organizations = await ai_contract_classifications.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.contract_documents,
        as: 'contract_document',
        
        where: filter.contract_document ? {
          [Op.or]: [
            { id: { [Op.in]: filter.contract_document.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.contract_document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.model_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_contract_classifications',
                        'model_name',
                        filter.model_name,
                    ),
                };
            }
            
            if (filter.predicted_category) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_contract_classifications',
                        'predicted_category',
                        filter.predicted_category,
                    ),
                };
            }
            
            if (filter.predicted_document_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_contract_classifications',
                        'predicted_document_type',
                        filter.predicted_document_type,
                    ),
                };
            }
            
            if (filter.disallow_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_contract_classifications',
                        'disallow_reason',
                        filter.disallow_reason,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

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

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

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

    
};

