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

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

        const document_versions = await db.document_versions.create(
            {
                id: data.id || undefined,
        
        revision: data.revision
        ||
        null
            ,
            
        version_status: data.version_status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
        effective_at: data.effective_at
        ||
        null
            ,
            
        change_summary: data.change_summary
        ||
        null
            ,
            
        version_content: data.version_content
        ||
        null
            ,
            
        hash_checksum: data.hash_checksum
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await document_versions.setDocument( data.document || null, {
            transaction,
        });
        
        await document_versions.setAuthor( data.author || null, {
            transaction,
        });
        

        

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

        return document_versions;
    }
    

    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_versionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                revision: item.revision
            ||
            null
            ,
            
                version_status: item.version_status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                approved_at: item.approved_at
            ||
            null
            ,
            
                effective_at: item.effective_at
            ||
            null
            ,
            
                change_summary: item.change_summary
            ||
            null
            ,
            
                version_content: item.version_content
            ||
            null
            ,
            
                hash_checksum: item.hash_checksum
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return document_versions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.revision !== undefined) updatePayload.revision = data.revision;
        
        
        if (data.version_status !== undefined) updatePayload.version_status = data.version_status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        if (data.effective_at !== undefined) updatePayload.effective_at = data.effective_at;
        
        
        if (data.change_summary !== undefined) updatePayload.change_summary = data.change_summary;
        
        
        if (data.version_content !== undefined) updatePayload.version_content = data.version_content;
        
        
        if (data.hash_checksum !== undefined) updatePayload.hash_checksum = data.hash_checksum;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.document !== undefined) {
            await document_versions.setDocument(
              
              data.document,
              
              { transaction }
            );
        }
        
        if (data.author !== undefined) {
            await document_versions.setAuthor(
              
              data.author,
              
              { transaction }
            );
        }
        

        
        

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

        return document_versions;
    }

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

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

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


        return document_versions;
    }

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

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

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

        await document_versions.destroy({
            transaction
        });

        return document_versions;
    }

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

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

        if (!document_versions) {
            return document_versions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.document = await document_versions.getDocument({
            transaction
        });
        
        
        output.author = await document_versions.getAuthor({
            transaction
        });
        
        
        output.version_files = await document_versions.getVersion_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.documents,
        as: 'document',
        
        where: filter.document ? {
          [Op.or]: [
            { id: { [Op.in]: filter.document.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.revision) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'revision',
                        filter.revision,
                    ),
                };
            }
            
            if (filter.change_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'change_summary',
                        filter.change_summary,
                    ),
                };
            }
            
            if (filter.version_content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'version_content',
                        filter.version_content,
                    ),
                };
            }
            
            if (filter.hash_checksum) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'hash_checksum',
                        filter.hash_checksum,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            submitted_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    effective_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

            
            if (filter.version_status) {
                where = {
                    ...where,
                version_status: filter.version_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.document_versions.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(
                        'document_versions',
                        'revision',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

