
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const TenantAccess = require('./tenantAccess');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Workflow_templatesDBApi {
    

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

        const workflow_templates = await db.workflow_templates.create(
            {
                id: data.id || undefined,
        
        template_name: data.template_name
        ||
        null
            ,
            
        workflow_type: data.workflow_type
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        risk_level: data.risk_level
        ||
        null
            ,
            
        owner_role: data.owner_role
        ||
        null
            ,
            
        source_trigger_type: data.source_trigger_type
        ||
        null
            ,
            
        recurrence_type: data.recurrence_type
        ||
        null
            ,
            
        default_required_fields: data.default_required_fields
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await workflow_templates.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        

        

        return workflow_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 workflow_templatesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                template_name: item.template_name
            ||
            null
            ,
            
                workflow_type: item.workflow_type
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                risk_level: item.risk_level
            ||
            null
            ,
            
                owner_role: item.owner_role
            ||
            null
            ,
            
                source_trigger_type: item.source_trigger_type
            ||
            null
            ,
            
                recurrence_type: item.recurrence_type
            ||
            null
            ,
            
                default_required_fields: item.default_required_fields
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return workflow_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 workflow_templates = await TenantAccess.findByPkOrThrow(db.workflow_templates, id, options);


        

        const updatePayload = {};
        
        if (data.template_name !== undefined) updatePayload.template_name = data.template_name;
        
        
        if (data.workflow_type !== undefined) updatePayload.workflow_type = data.workflow_type;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.risk_level !== undefined) updatePayload.risk_level = data.risk_level;
        
        
        if (data.owner_role !== undefined) updatePayload.owner_role = data.owner_role;
        
        
        if (data.source_trigger_type !== undefined) updatePayload.source_trigger_type = data.source_trigger_type;
        
        
        if (data.recurrence_type !== undefined) updatePayload.recurrence_type = data.recurrence_type;
        
        
        if (data.default_required_fields !== undefined) updatePayload.default_required_fields = data.default_required_fields;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await workflow_templates.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        

        

        return workflow_templates;
    }

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

        const workflow_templates = await TenantAccess.findAllByIds(db.workflow_templates, ids, options);

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


        return workflow_templates;
    }

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

        const workflow_templates = await TenantAccess.findByPkOrThrow(db.workflow_templates, id, options);

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

        await workflow_templates.destroy({
            transaction
        });

        return workflow_templates;
    }

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

        const workflow_templates = await TenantAccess.findOne(db.workflow_templates, where, options);

        if (!workflow_templates) {
            return workflow_templates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await workflow_templates.getOrganization({
            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.organizations,
        as: 'organization',
        
      },



    ];

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

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

            
            

            

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

            
            if (filter.workflow_type) {
                where = {
                    ...where,
                workflow_type: filter.workflow_type,
            };
            }
            
            if (filter.risk_level) {
                where = {
                    ...where,
                risk_level: filter.risk_level,
            };
            }
            
            if (filter.owner_role) {
                where = {
                    ...where,
                owner_role: filter.owner_role,
            };
            }
            
            if (filter.source_trigger_type) {
                where = {
                    ...where,
                source_trigger_type: filter.source_trigger_type,
            };
            }
            
            if (filter.recurrence_type) {
                where = {
                    ...where,
                recurrence_type: filter.recurrence_type,
            };
            }
            


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[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.workflow_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(
                        'workflow_templates',
                        'template_name',
                        query,
                    ),
                ],
            };
        }

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

    
};

