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

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

        const process_steps = await db.process_steps.create(
            {
                id: data.id || undefined,
        
        step_number: data.step_number
        ||
        null
            ,
            
        step_title: data.step_title
        ||
        null
            ,
            
        step_description: data.step_description
        ||
        null
            ,
            
        icon_name: data.icon_name
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await process_steps.setQuality_process( data.quality_process || null, {
            transaction,
        });
        

        

        

        return process_steps;
    }
    

    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 process_stepsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                step_number: item.step_number
            ||
            null
            ,
            
                step_title: item.step_title
            ||
            null
            ,
            
                step_description: item.step_description
            ||
            null
            ,
            
                icon_name: item.icon_name
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return process_steps;
    }

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

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


        

        const updatePayload = {};
        
        if (data.step_number !== undefined) updatePayload.step_number = data.step_number;
        
        
        if (data.step_title !== undefined) updatePayload.step_title = data.step_title;
        
        
        if (data.step_description !== undefined) updatePayload.step_description = data.step_description;
        
        
        if (data.icon_name !== undefined) updatePayload.icon_name = data.icon_name;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.quality_process !== undefined) {
            await process_steps.setQuality_process(
              
              data.quality_process,
              
              { transaction }
            );
        }
        

        
        

        

        return process_steps;
    }

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

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

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


        return process_steps;
    }

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

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

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

        await process_steps.destroy({
            transaction
        });

        return process_steps;
    }

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

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

        if (!process_steps) {
            return process_steps;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quality_process = await process_steps.getQuality_process({
            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.quality_processes,
        as: 'quality_process',
        
        where: filter.quality_process ? {
          [Op.or]: [
            { id: { [Op.in]: filter.quality_process.split('|').map(term => Utils.uuid(term)) } },
            {
              headline: {
                [Op.or]: filter.quality_process.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.step_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'process_steps',
                        'step_title',
                        filter.step_title,
                    ),
                };
            }
            
            if (filter.step_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'process_steps',
                        'step_description',
                        filter.step_description,
                    ),
                };
            }
            
            if (filter.icon_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'process_steps',
                        'icon_name',
                        filter.icon_name,
                    ),
                };
            }
            

            
            

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

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

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

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

            


      



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

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

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

    
};

