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

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

        const legal_templates = await db.legal_templates.create(
            {
                id: data.id || undefined,
        
        template_name: data.template_name
        ||
        null
            ,
            
        template_category: data.template_category
        ||
        null
            ,
            
        jurisdiction: data.jurisdiction
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        template_body: data.template_body
        ||
        null
            ,
            
        is_public: data.is_public
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await legal_templates.setOwner( data.owner || null, {
            transaction,
        });
        
        await legal_templates.setSource_file( data.source_file || null, {
            transaction,
        });
        

        

        

        return legal_templates;
    }
    

    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 legal_templatesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                template_name: item.template_name
            ||
            null
            ,
            
                template_category: item.template_category
            ||
            null
            ,
            
                jurisdiction: item.jurisdiction
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                template_body: item.template_body
            ||
            null
            ,
            
                is_public: item.is_public
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return legal_templates;
    }

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

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


        

        const updatePayload = {};
        
        if (data.template_name !== undefined) updatePayload.template_name = data.template_name;
        
        
        if (data.template_category !== undefined) updatePayload.template_category = data.template_category;
        
        
        if (data.jurisdiction !== undefined) updatePayload.jurisdiction = data.jurisdiction;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.template_body !== undefined) updatePayload.template_body = data.template_body;
        
        
        if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner !== undefined) {
            await legal_templates.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.source_file !== undefined) {
            await legal_templates.setSource_file(
              
              data.source_file,
              
              { transaction }
            );
        }
        

        
        

        

        return legal_templates;
    }

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

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

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


        return legal_templates;
    }

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

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

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

        await legal_templates.destroy({
            transaction
        });

        return legal_templates;
    }

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

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

        if (!legal_templates) {
            return legal_templates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.template_fields_template = await legal_templates.getTemplate_fields_template({
            transaction
        });
        
        
        output.generated_documents_template = await legal_templates.getGenerated_documents_template({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner = await legal_templates.getOwner({
            transaction
        });
        
        
        output.source_file = await legal_templates.getSource_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.files,
        as: 'source_file',
        
        where: filter.source_file ? {
          [Op.or]: [
            { id: { [Op.in]: filter.source_file.split('|').map(term => Utils.uuid(term)) } },
            {
              file_name: {
                [Op.or]: filter.source_file.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.template_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'legal_templates',
                        'template_name',
                        filter.template_name,
                    ),
                };
            }
            
            if (filter.jurisdiction) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'legal_templates',
                        'jurisdiction',
                        filter.jurisdiction,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'legal_templates',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.template_body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'legal_templates',
                        'template_body',
                        filter.template_body,
                    ),
                };
            }
            

            
            

            

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

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


      

      



            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.legal_templates.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(
                        'legal_templates',
                        'template_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

