
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,
        
        version_number: data.version_number
        ||
        null
            ,
            
        change_source: data.change_source
        ||
        null
            ,
            
        content_snapshot: data.content_snapshot
        ||
        null
            ,
            
        saved_at: data.saved_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        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,
                
                version_number: item.version_number
            ||
            null
            ,
            
                change_source: item.change_source
            ||
            null
            ,
            
                content_snapshot: item.content_snapshot
            ||
            null
            ,
            
                saved_at: item.saved_at
            ||
            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
        

        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.version_number !== undefined) updatePayload.version_number = data.version_number;
        
        
        if (data.change_source !== undefined) updatePayload.change_source = data.change_source;
        
        
        if (data.content_snapshot !== undefined) updatePayload.content_snapshot = data.content_snapshot;
        
        
        if (data.saved_at !== undefined) updatePayload.saved_at = data.saved_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        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
        });
        
        

        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.generated_documents,
        as: 'document',
        
        where: filter.document ? {
          [Op.or]: [
            { id: { [Op.in]: filter.document.split('|').map(term => Utils.uuid(term)) } },
            {
              document_title: {
                [Op.or]: filter.document.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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


      



            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',
                        'change_source',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

