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

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

        const contract_documents = await db.contract_documents.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        document_source: data.document_source
        ||
        null
            ,
            
        content_hash: data.content_hash
        ||
        null
            ,
            
        current_revision_number: data.current_revision_number
        ||
        null
            ,
            
        is_locked: data.is_locked
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await contract_documents.setContract_folder( data.contract_folder || null, {
            transaction,
        });
        
        await contract_documents.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.contract_documents.getTableName(),
                belongsToColumn: 'original_file',
                belongsToId: contract_documents.id,
            },
            data.original_file,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.contract_documents.getTableName(),
                belongsToColumn: 'working_file',
                belongsToId: contract_documents.id,
            },
            data.working_file,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.contract_documents.getTableName(),
                belongsToColumn: 'final_signed_file',
                belongsToId: contract_documents.id,
            },
            data.final_signed_file,
            options,
        );
        

        return contract_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 contract_documentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                document_source: item.document_source
            ||
            null
            ,
            
                content_hash: item.content_hash
            ||
            null
            ,
            
                current_revision_number: item.current_revision_number
            ||
            null
            ,
            
                is_locked: item.is_locked
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return contract_documents;
    }

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.document_source !== undefined) updatePayload.document_source = data.document_source;
        
        
        if (data.content_hash !== undefined) updatePayload.content_hash = data.content_hash;
        
        
        if (data.current_revision_number !== undefined) updatePayload.current_revision_number = data.current_revision_number;
        
        
        if (data.is_locked !== undefined) updatePayload.is_locked = data.is_locked;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.contract_folder !== undefined) {
            await contract_documents.setContract_folder(
              
              data.contract_folder,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await contract_documents.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.contract_documents.getTableName(),
                belongsToColumn: 'original_file',
                belongsToId: contract_documents.id,
            },
            data.original_file,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.contract_documents.getTableName(),
                belongsToColumn: 'working_file',
                belongsToId: contract_documents.id,
            },
            data.working_file,
            options,
        );
        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.contract_documents.getTableName(),
                belongsToColumn: 'final_signed_file',
                belongsToId: contract_documents.id,
            },
            data.final_signed_file,
            options,
        );
        

        return contract_documents;
    }

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

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

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


        return contract_documents;
    }

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

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

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

        await contract_documents.destroy({
            transaction
        });

        return contract_documents;
    }

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

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

        if (!contract_documents) {
            return contract_documents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.contract_data_fields_contract_document = await contract_documents.getContract_data_fields_contract_document({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.signing_actions_contract_document = await contract_documents.getSigning_actions_contract_document({
            transaction
        });
        
        
        output.document_revisions_contract_document = await contract_documents.getDocument_revisions_contract_document({
            transaction
        });
        
        
        
        
        
        
        output.ai_contract_classifications_contract_document = await contract_documents.getAi_contract_classifications_contract_document({
            transaction
        });
        
        
        
        
        
        
        output.contract_folder = await contract_documents.getContract_folder({
            transaction
        });
        
        
        output.original_file = await contract_documents.getOriginal_file({
            transaction
        });
        
        
        output.working_file = await contract_documents.getWorking_file({
            transaction
        });
        
        
        output.final_signed_file = await contract_documents.getFinal_signed_file({
            transaction
        });
        
        
        output.organizations = await contract_documents.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_folders,
        as: 'contract_folder',
        
        where: filter.contract_folder ? {
          [Op.or]: [
            { id: { [Op.in]: filter.contract_folder.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.contract_folder.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

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

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

    ];

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

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

            
            

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

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

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

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

            
            if (filter.document_source) {
                where = {
                    ...where,
                document_source: filter.document_source,
            };
            }
            
            if (filter.is_locked) {
                where = {
                    ...where,
                is_locked: filter.is_locked,
            };
            }
            


      

      
      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.contract_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

    
};

