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

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

        const batches = await db.batches.create(
            {
                id: data.id || undefined,
        
        batch_number: data.batch_number
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        manufacture_start_at: data.manufacture_start_at
        ||
        null
            ,
            
        manufacture_end_at: data.manufacture_end_at
        ||
        null
            ,
            
        quantity_planned: data.quantity_planned
        ||
        null
            ,
            
        quantity_produced: data.quantity_produced
        ||
        null
            ,
            
        quantity_released: data.quantity_released
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await batches.setProduct( data.product || null, {
            transaction,
        });
        
        await batches.setBmr_document( data.bmr_document || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.batches.getTableName(),
                belongsToColumn: 'batch_record_files',
                belongsToId: batches.id,
            },
            data.batch_record_files,
            options,
        );
        

        return batches;
    }
    

    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 batchesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                batch_number: item.batch_number
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                manufacture_start_at: item.manufacture_start_at
            ||
            null
            ,
            
                manufacture_end_at: item.manufacture_end_at
            ||
            null
            ,
            
                quantity_planned: item.quantity_planned
            ||
            null
            ,
            
                quantity_produced: item.quantity_produced
            ||
            null
            ,
            
                quantity_released: item.quantity_released
            ||
            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 batches = await db.batches.bulkCreate(batchesData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < batches.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.batches.getTableName(),
                    belongsToColumn: 'batch_record_files',
                    belongsToId: batches[i].id,
                },
                data[i].batch_record_files,
                options,
            );
        }
        

        return batches;
    }

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

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


        

        const updatePayload = {};
        
        if (data.batch_number !== undefined) updatePayload.batch_number = data.batch_number;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.manufacture_start_at !== undefined) updatePayload.manufacture_start_at = data.manufacture_start_at;
        
        
        if (data.manufacture_end_at !== undefined) updatePayload.manufacture_end_at = data.manufacture_end_at;
        
        
        if (data.quantity_planned !== undefined) updatePayload.quantity_planned = data.quantity_planned;
        
        
        if (data.quantity_produced !== undefined) updatePayload.quantity_produced = data.quantity_produced;
        
        
        if (data.quantity_released !== undefined) updatePayload.quantity_released = data.quantity_released;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.product !== undefined) {
            await batches.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        
        if (data.bmr_document !== undefined) {
            await batches.setBmr_document(
              
              data.bmr_document,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.batches.getTableName(),
                belongsToColumn: 'batch_record_files',
                belongsToId: batches.id,
            },
            data.batch_record_files,
            options,
        );
        

        return batches;
    }

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

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

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


        return batches;
    }

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

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

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

        await batches.destroy({
            transaction
        });

        return batches;
    }

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

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

        if (!batches) {
            return batches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.certificates_of_analysis_batch = await batches.getCertificates_of_analysis_batch({
            transaction
        });
        
        
        
        
        
        
        output.nonconformances_batch = await batches.getNonconformances_batch({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.product = await batches.getProduct({
            transaction
        });
        
        
        output.bmr_document = await batches.getBmr_document({
            transaction
        });
        
        
        output.batch_record_files = await batches.getBatch_record_files({
            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.products,
        as: 'product',
        
        where: filter.product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
            {
              product_name: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



      {
        model: db.file,
        as: 'batch_record_files',
      },

    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            manufacture_start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    manufacture_end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    quantity_planned: {
                    ...where.quantity_planned,
                            [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.quantity_releasedRange) {
                const [start, end] = filter.quantity_releasedRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    quantity_released: {
                    ...where.quantity_released,
                            [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.batches.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(
                        'batches',
                        'batch_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

