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

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

        const lots = await db.lots.create(
            {
                id: data.id || undefined,
        
        lot_code: data.lot_code
        ||
        null
            ,
            
        supplier_lot_code: data.supplier_lot_code
        ||
        null
            ,
            
        received_at: data.received_at
        ||
        null
            ,
            
        manufactured_at: data.manufactured_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        quality_status: data.quality_status
        ||
        null
            ,
            
        certificate_number: data.certificate_number
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await lots.setItem( data.item || null, {
            transaction,
        });
        
        await lots.setSupplier( data.supplier || null, {
            transaction,
        });
        

        

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

        return 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 lotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                lot_code: item.lot_code
            ||
            null
            ,
            
                supplier_lot_code: item.supplier_lot_code
            ||
            null
            ,
            
                received_at: item.received_at
            ||
            null
            ,
            
                manufactured_at: item.manufactured_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                quality_status: item.quality_status
            ||
            null
            ,
            
                certificate_number: item.certificate_number
            ||
            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 lots = await db.lots.bulkCreate(lotsData, { transaction });

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

        return lots;
    }

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

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


        

        const updatePayload = {};
        
        if (data.lot_code !== undefined) updatePayload.lot_code = data.lot_code;
        
        
        if (data.supplier_lot_code !== undefined) updatePayload.supplier_lot_code = data.supplier_lot_code;
        
        
        if (data.received_at !== undefined) updatePayload.received_at = data.received_at;
        
        
        if (data.manufactured_at !== undefined) updatePayload.manufactured_at = data.manufactured_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.quality_status !== undefined) updatePayload.quality_status = data.quality_status;
        
        
        if (data.certificate_number !== undefined) updatePayload.certificate_number = data.certificate_number;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.item !== undefined) {
            await lots.setItem(
              
              data.item,
              
              { transaction }
            );
        }
        
        if (data.supplier !== undefined) {
            await lots.setSupplier(
              
              data.supplier,
              
              { transaction }
            );
        }
        

        
        

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

        return lots;
    }

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

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

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


        return lots;
    }

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

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

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

        await lots.destroy({
            transaction
        });

        return lots;
    }

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

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

        if (!lots) {
            return lots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.inventory_transactions_lot = await lots.getInventory_transactions_lot({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.material_issue_lines_lot = await lots.getMaterial_issue_lines_lot({
            transaction
        });
        
        
        
        output.receipt_lines_lot = await lots.getReceipt_lines_lot({
            transaction
        });
        
        
        
        output.shipment_lines_lot = await lots.getShipment_lines_lot({
            transaction
        });
        
        
        
        
        output.qa_inspections_lot = await lots.getQa_inspections_lot({
            transaction
        });
        
        
        
        output.nonconformances_lot = await lots.getNonconformances_lot({
            transaction
        });
        
        
        
        
        output.item = await lots.getItem({
            transaction
        });
        
        
        output.supplier = await lots.getSupplier({
            transaction
        });
        
        
        output.certificates = await lots.getCertificates({
            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.items,
        as: 'item',
        
        where: filter.item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.item.split('|').map(term => Utils.uuid(term)) } },
            {
              item_name: {
                [Op.or]: filter.item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

            
            if (filter.lot_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lots',
                        'lot_code',
                        filter.lot_code,
                    ),
                };
            }
            
            if (filter.supplier_lot_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lots',
                        'supplier_lot_code',
                        filter.supplier_lot_code,
                    ),
                };
            }
            
            if (filter.certificate_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lots',
                        'certificate_number',
                        filter.certificate_number,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'lots',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

            
            if (filter.quality_status) {
                where = {
                    ...where,
                quality_status: filter.quality_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.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(
                        'lots',
                        'lot_code',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

