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

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

        const production_lines = await db.production_lines.create(
            {
                id: data.id || undefined,
        
        line_name: data.line_name
        ||
        null
            ,
            
        line_code: data.line_code
        ||
        null
            ,
            
        line_status: data.line_status
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await production_lines.setWork_center( data.work_center || null, {
            transaction,
        });
        

        

        

        return production_lines;
    }
    

    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 production_linesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                line_name: item.line_name
            ||
            null
            ,
            
                line_code: item.line_code
            ||
            null
            ,
            
                line_status: item.line_status
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return production_lines;
    }

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

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


        

        const updatePayload = {};
        
        if (data.line_name !== undefined) updatePayload.line_name = data.line_name;
        
        
        if (data.line_code !== undefined) updatePayload.line_code = data.line_code;
        
        
        if (data.line_status !== undefined) updatePayload.line_status = data.line_status;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.work_center !== undefined) {
            await production_lines.setWork_center(
              
              data.work_center,
              
              { transaction }
            );
        }
        

        
        

        

        return production_lines;
    }

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

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

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


        return production_lines;
    }

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

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

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

        await production_lines.destroy({
            transaction
        });

        return production_lines;
    }

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

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

        if (!production_lines) {
            return production_lines;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.work_orders_production_line = await production_lines.getWork_orders_production_line({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.work_center = await production_lines.getWork_center({
            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.work_centers,
        as: 'work_center',
        
        where: filter.work_center ? {
          [Op.or]: [
            { id: { [Op.in]: filter.work_center.split('|').map(term => Utils.uuid(term)) } },
            {
              work_center_name: {
                [Op.or]: filter.work_center.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.line_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_lines',
                        'line_name',
                        filter.line_name,
                    ),
                };
            }
            
            if (filter.line_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_lines',
                        'line_code',
                        filter.line_code,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_lines',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

            

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

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


      



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

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

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

    
};

