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

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

        const quality_holds = await db.quality_holds.create(
            {
                id: data.id || undefined,
        
        hold_number: data.hold_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        hold_started_at: data.hold_started_at
        ||
        null
            ,
            
        hold_released_at: data.hold_released_at
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quality_holds.setPlant( data.plant || null, {
            transaction,
        });
        
        await quality_holds.setItem( data.item || null, {
            transaction,
        });
        
        await quality_holds.setLot( data.lot || null, {
            transaction,
        });
        
        await quality_holds.setLocation( data.location || null, {
            transaction,
        });
        
        await quality_holds.setPlaced_by( data.placed_by || null, {
            transaction,
        });
        
        await quality_holds.setReleased_by( data.released_by || null, {
            transaction,
        });
        

        

        

        return quality_holds;
    }
    

    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 quality_holdsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                hold_number: item.hold_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                hold_started_at: item.hold_started_at
            ||
            null
            ,
            
                hold_released_at: item.hold_released_at
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return quality_holds;
    }

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

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


        

        const updatePayload = {};
        
        if (data.hold_number !== undefined) updatePayload.hold_number = data.hold_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.hold_started_at !== undefined) updatePayload.hold_started_at = data.hold_started_at;
        
        
        if (data.hold_released_at !== undefined) updatePayload.hold_released_at = data.hold_released_at;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.plant !== undefined) {
            await quality_holds.setPlant(
              
              data.plant,
              
              { transaction }
            );
        }
        
        if (data.item !== undefined) {
            await quality_holds.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.lot !== undefined) {
            await quality_holds.setLot(
              
              data.lot,
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await quality_holds.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        
        if (data.placed_by !== undefined) {
            await quality_holds.setPlaced_by(
              
              data.placed_by,
              
              { transaction }
            );
        }
        
        if (data.released_by !== undefined) {
            await quality_holds.setReleased_by(
              
              data.released_by,
              
              { transaction }
            );
        }
        

        
        

        

        return quality_holds;
    }

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

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

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


        return quality_holds;
    }

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

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

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

        await quality_holds.destroy({
            transaction
        });

        return quality_holds;
    }

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

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

        if (!quality_holds) {
            return quality_holds;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.plant = await quality_holds.getPlant({
            transaction
        });
        
        
        output.item = await quality_holds.getItem({
            transaction
        });
        
        
        output.lot = await quality_holds.getLot({
            transaction
        });
        
        
        output.location = await quality_holds.getLocation({
            transaction
        });
        
        
        output.placed_by = await quality_holds.getPlaced_by({
            transaction
        });
        
        
        output.released_by = await quality_holds.getReleased_by({
            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.plants,
        as: 'plant',
        
        where: filter.plant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.plant.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.plant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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

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



    ];

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

            
            if (filter.hold_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quality_holds',
                        'hold_number',
                        filter.hold_number,
                    ),
                };
            }
            
            if (filter.reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'quality_holds',
                        'reason',
                        filter.reason,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    hold_started_at: {
                    ...where.hold_started_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.hold_released_atRange) {
                const [start, end] = filter.hold_released_atRange;

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.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.quality_holds.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(
                        'quality_holds',
                        'hold_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

