
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,
        
        title: data.title
        ||
        null
            ,
            
        version_label: data.version_label
        ||
        null
            ,
            
        template_source: data.template_source
        ||
        null
            ,
            
        template_body: data.template_body
        ||
        null
            ,
            
        is_public: data.is_public
        ||
        false
        
            ,
            
        is_active: data.is_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.setTenant( data.tenant || null, {
            transaction,
        });
        
        await document_templates.setOwner_user( data.owner_user || null, {
            transaction,
        });
        
        await document_templates.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.document_templates.getTableName(),
                belongsToColumn: 'template_file',
                belongsToId: document_templates.id,
            },
            data.template_file,
            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,
                
                title: item.title
            ||
            null
            ,
            
                version_label: item.version_label
            ||
            null
            ,
            
                template_source: item.template_source
            ||
            null
            ,
            
                template_body: item.template_body
            ||
            null
            ,
            
                is_public: item.is_public
            ||
            false
        
            ,
            
                is_active: item.is_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_file',
                    belongsToId: document_templates[i].id,
                },
                data[i].template_file,
                options,
            );
        }
        

        return document_templates;
    }

    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_templates = await db.document_templates.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.version_label !== undefined) updatePayload.version_label = data.version_label;
        
        
        if (data.template_source !== undefined) updatePayload.template_source = data.template_source;
        
        
        if (data.template_body !== undefined) updatePayload.template_body = data.template_body;
        
        
        if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_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.tenant !== undefined) {
            await document_templates.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.owner_user !== undefined) {
            await document_templates.setOwner_user(
              
              data.owner_user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await document_templates.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.document_templates.getTableName(),
                belongsToColumn: 'template_file',
                belongsToId: document_templates.id,
            },
            data.template_file,
            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.contract_folders_document_template = await document_templates.getContract_folders_document_template({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.document_type = await document_templates.getDocument_type({
            transaction
        });
        
        
        output.tenant = await document_templates.getTenant({
            transaction
        });
        
        
        output.owner_user = await document_templates.getOwner_user({
            transaction
        });
        
        
        output.template_file = await document_templates.getTemplate_file({
            transaction
        });
        
        
        output.organizations = await document_templates.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.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              trade_name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



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

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_templates',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.version_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'document_templates',
                        'version_label',
                        filter.version_label,
                    ),
                };
            }
            
            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_source) {
                where = {
                    ...where,
                template_source: filter.template_source,
            };
            }
            
            if (filter.is_public) {
                where = {
                    ...where,
                is_public: filter.is_public,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

      

      

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

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

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

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

    
};

