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

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

        const production_lots = await db.production_lots.create(
            {
                id: data.id || undefined,
        
        lot_number: data.lot_number
        ||
        null
            ,
            
        started_on: data.started_on
        ||
        null
            ,
            
        completed_on: data.completed_on
        ||
        null
            ,
            
        quantity_produced: data.quantity_produced
        ||
        null
            ,
            
        release_status: data.release_status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await production_lots.setProduction_order( data.production_order || null, {
            transaction,
        });
        
        await production_lots.setStored_location( data.stored_location || null, {
            transaction,
        });
        

        

        

        return production_lots;
    }
    

    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_lotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                lot_number: item.lot_number
            ||
            null
            ,
            
                started_on: item.started_on
            ||
            null
            ,
            
                completed_on: item.completed_on
            ||
            null
            ,
            
                quantity_produced: item.quantity_produced
            ||
            null
            ,
            
                release_status: item.release_status
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return production_lots;
    }

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

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


        

        const updatePayload = {};
        
        if (data.lot_number !== undefined) updatePayload.lot_number = data.lot_number;
        
        
        if (data.started_on !== undefined) updatePayload.started_on = data.started_on;
        
        
        if (data.completed_on !== undefined) updatePayload.completed_on = data.completed_on;
        
        
        if (data.quantity_produced !== undefined) updatePayload.quantity_produced = data.quantity_produced;
        
        
        if (data.release_status !== undefined) updatePayload.release_status = data.release_status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.production_order !== undefined) {
            await production_lots.setProduction_order(
              
              data.production_order,
              
              { transaction }
            );
        }
        
        if (data.stored_location !== undefined) {
            await production_lots.setStored_location(
              
              data.stored_location,
              
              { transaction }
            );
        }
        

        
        

        

        return production_lots;
    }

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

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

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


        return production_lots;
    }

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

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

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

        await production_lots.destroy({
            transaction
        });

        return production_lots;
    }

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

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

        if (!production_lots) {
            return production_lots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.qa_inspections_production_lot = await production_lots.getQa_inspections_production_lot({
            transaction
        });
        
        
        
        
        
        output.nonconformances_production_lot = await production_lots.getNonconformances_production_lot({
            transaction
        });
        
        
        
        
        
        output.production_order = await production_lots.getProduction_order({
            transaction
        });
        
        
        output.stored_location = await production_lots.getStored_location({
            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.production_orders,
        as: 'production_order',
        
        where: filter.production_order ? {
          [Op.or]: [
            { id: { [Op.in]: filter.production_order.split('|').map(term => Utils.uuid(term)) } },
            {
              order_number: {
                [Op.or]: filter.production_order.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.lot_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_lots',
                        'lot_number',
                        filter.lot_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'production_lots',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.release_status) {
                where = {
                    ...where,
                release_status: filter.release_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_lots.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_lots',
                        'lot_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

