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

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

        const generated_documents = await db.generated_documents.create(
            {
                id: data.id || undefined,
        
        document_title: data.document_title
        ||
        null
            ,
            
        document_type: data.document_type
        ||
        null
            ,
            
        format: data.format
        ||
        null
            ,
            
        content: data.content
        ||
        null
            ,
            
        last_edited_at: data.last_edited_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await generated_documents.setOwner( data.owner || null, {
            transaction,
        });
        
        await generated_documents.setMatter( data.matter || null, {
            transaction,
        });
        
        await generated_documents.setTemplate( data.template || null, {
            transaction,
        });
        
        await generated_documents.setExport_file( data.export_file || null, {
            transaction,
        });
        

        

        

        return generated_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 generated_documentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                document_title: item.document_title
            ||
            null
            ,
            
                document_type: item.document_type
            ||
            null
            ,
            
                format: item.format
            ||
            null
            ,
            
                content: item.content
            ||
            null
            ,
            
                last_edited_at: item.last_edited_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return generated_documents;
    }

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

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


        

        const updatePayload = {};
        
        if (data.document_title !== undefined) updatePayload.document_title = data.document_title;
        
        
        if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
        
        
        if (data.format !== undefined) updatePayload.format = data.format;
        
        
        if (data.content !== undefined) updatePayload.content = data.content;
        
        
        if (data.last_edited_at !== undefined) updatePayload.last_edited_at = data.last_edited_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner !== undefined) {
            await generated_documents.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.matter !== undefined) {
            await generated_documents.setMatter(
              
              data.matter,
              
              { transaction }
            );
        }
        
        if (data.template !== undefined) {
            await generated_documents.setTemplate(
              
              data.template,
              
              { transaction }
            );
        }
        
        if (data.export_file !== undefined) {
            await generated_documents.setExport_file(
              
              data.export_file,
              
              { transaction }
            );
        }
        

        
        

        

        return generated_documents;
    }

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

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

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


        return generated_documents;
    }

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

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

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

        await generated_documents.destroy({
            transaction
        });

        return generated_documents;
    }

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

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

        if (!generated_documents) {
            return generated_documents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.document_versions_document = await generated_documents.getDocument_versions_document({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner = await generated_documents.getOwner({
            transaction
        });
        
        
        output.matter = await generated_documents.getMatter({
            transaction
        });
        
        
        output.template = await generated_documents.getTemplate({
            transaction
        });
        
        
        output.export_file = await generated_documents.getExport_file({
            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.users,
        as: 'owner',
        
        where: filter.owner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



    ];

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

            
            if (filter.document_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'generated_documents',
                        'document_title',
                        filter.document_title,
                    ),
                };
            }
            
            if (filter.content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'generated_documents',
                        'content',
                        filter.content,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

      

      



            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.generated_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, ) {
        let where = {};
        
        

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

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

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

    
};

