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

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

        const document_revisions = await db.document_revisions.create(
            {
                id: data.id || undefined,
        
        revision_number: data.revision_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        proposed_at: data.proposed_at
        ||
        null
            ,
            
        change_summary: data.change_summary
        ||
        null
            ,
            
        content_hash: data.content_hash
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

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

        return document_revisions;
    }
    

    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 document_revisionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                revision_number: item.revision_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                proposed_at: item.proposed_at
            ||
            null
            ,
            
                change_summary: item.change_summary
            ||
            null
            ,
            
                content_hash: item.content_hash
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return document_revisions;
    }

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


        

        const updatePayload = {};
        
        if (data.revision_number !== undefined) updatePayload.revision_number = data.revision_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.proposed_at !== undefined) updatePayload.proposed_at = data.proposed_at;
        
        
        if (data.change_summary !== undefined) updatePayload.change_summary = data.change_summary;
        
        
        if (data.content_hash !== undefined) updatePayload.content_hash = data.content_hash;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return document_revisions;
    }

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

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

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


        return document_revisions;
    }

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

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

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

        await document_revisions.destroy({
            transaction
        });

        return document_revisions;
    }

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

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

        if (!document_revisions) {
            return document_revisions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.revision_approvals_document_revision = await document_revisions.getRevision_approvals_document_revision({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.contract_document = await document_revisions.getContract_document({
            transaction
        });
        
        
        output.proposed_by_participant = await document_revisions.getProposed_by_participant({
            transaction
        });
        
        
        output.revision_file = await document_revisions.getRevision_file({
            transaction
        });
        
        
        output.organizations = await document_revisions.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.contract_participants,
        as: 'proposed_by_participant',
        
        where: filter.proposed_by_participant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.proposed_by_participant.split('|').map(term => Utils.uuid(term)) } },
            {
              display_name: {
                [Op.or]: filter.proposed_by_participant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

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

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    proposed_at: {
                    ...where.proposed_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.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.document_revisions.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(
                        'document_revisions',
                        'change_summary',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

