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

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

        const document_templates = await db.document_templates.create(
            {
                id: data.id || undefined,
        
        template_name: data.template_name
        ||
        null
            ,
            
        template_code: data.template_code
        ||
        null
            ,
            
        template_family: data.template_family
        ||
        null
            ,
            
        purpose: data.purpose
        ||
        null
            ,
            
        template_body: data.template_body
        ||
        null
            ,
            
        format: data.format
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await document_templates.setDocument_type( data.document_type || null, {
            transaction,
        });
        

        
        await document_templates.setMapped_clauses(data.mapped_clauses || [], {
            transaction,
        });
        

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

        return document_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 document_templatesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                template_name: item.template_name
            ||
            null
            ,
            
                template_code: item.template_code
            ||
            null
            ,
            
                template_family: item.template_family
            ||
            null
            ,
            
                purpose: item.purpose
            ||
            null
            ,
            
                template_body: item.template_body
            ||
            null
            ,
            
                format: item.format
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return document_templates;
    }

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

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


        

        const updatePayload = {};
        
        if (data.template_name !== undefined) updatePayload.template_name = data.template_name;
        
        
        if (data.template_code !== undefined) updatePayload.template_code = data.template_code;
        
        
        if (data.template_family !== undefined) updatePayload.template_family = data.template_family;
        
        
        if (data.purpose !== undefined) updatePayload.purpose = data.purpose;
        
        
        if (data.template_body !== undefined) updatePayload.template_body = data.template_body;
        
        
        if (data.format !== undefined) updatePayload.format = data.format;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.document_type !== undefined) {
            await document_templates.setDocument_type(
              
              data.document_type,
              
              { transaction }
            );
        }
        

        
        
        if (data.mapped_clauses !== undefined) {
            await document_templates.setMapped_clauses(data.mapped_clauses, { transaction });
        }
        

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

        return document_templates;
    }

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

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

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


        return document_templates;
    }

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

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

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

        await document_templates.destroy({
            transaction
        });

        return document_templates;
    }

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

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

        if (!document_templates) {
            return document_templates;
        }

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

        
        
        
        
        
        
        
        
        output.documents_template = await document_templates.getDocuments_template({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.document_type = await document_templates.getDocument_type({
            transaction
        });
        
        
        output.template_files = await document_templates.getTemplate_files({
            transaction
        });
        
        
        output.mapped_clauses = await document_templates.getMapped_clauses({
            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.document_types,
        as: 'document_type',
        
        where: filter.document_type ? {
          [Op.or]: [
            { id: { [Op.in]: filter.document_type.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.document_type.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },


      {
        model: db.clauses,
        as: 'mapped_clauses',
        required: false,
      },


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

    ];

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

            
            if (filter.template_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_templates',
                        'template_name',
                        filter.template_name,
                    ),
                };
            }
            
            if (filter.template_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_templates',
                        'template_code',
                        filter.template_code,
                    ),
                };
            }
            
            if (filter.purpose) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_templates',
                        'purpose',
                        filter.purpose,
                    ),
                };
            }
            
            if (filter.template_body) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_templates',
                        'template_body',
                        filter.template_body,
                    ),
                };
            }
            

            
            

            

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

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


      


      if (filter.mapped_clauses) {
        const searchTerms = filter.mapped_clauses.split('|');

        include = [
          {
            model: db.clauses,
            as: 'mapped_clauses_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  clause_code: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

    
};

