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

        
        await document_versions.setDocument( data.document || null, {
            transaction,
        });
        
        await document_versions.setEditor( data.editor || null, {
            transaction,
        });
        
        await document_versions.setOrganizations( data.organizations || 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
            ,
            
                content_markdown: item.content_markdown
            ||
            null
            ,
            
                saved_at: item.saved_at
            ||
            null
            ,
            
                change_summary: item.change_summary
            ||
            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 globalAccess = currentUser.app_role?.globalAccess;

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

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

        
        
        if (data.document !== undefined) {
            await document_versions.setDocument(
              
              data.document,
              
              { transaction }
            );
        }
        
        if (data.editor !== undefined) {
            await document_versions.setEditor(
              
              data.editor,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await document_versions.setOrganizations(
              
              data.organizations,
              
              { 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
        });
        
        
        output.editor = await document_versions.getEditor({
            transaction
        });
        
        
        output.organizations = await document_versions.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.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: 'editor',
        
        where: filter.editor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.editor.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.editor.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.content_markdown) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'content_markdown',
                        filter.content_markdown,
                    ),
                };
            }
            
            if (filter.change_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_versions',
                        'change_summary',
                        filter.change_summary,
                    ),
                };
            }
            

            
            

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

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

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

    
};

