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

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

        const sample_requests = await db.sample_requests.create(
            {
                id: data.id || undefined,
        
        sample_request_number: data.sample_request_number
        ||
        null
            ,
            
        sample_quantity: data.sample_quantity
        ||
        null
            ,
            
        requested_at: data.requested_at
        ||
        null
            ,
            
        needed_by: data.needed_by
        ||
        null
            ,
            
        sample_status: data.sample_status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await sample_requests.setAccount( data.account || null, {
            transaction,
        });
        
        await sample_requests.setLocation( data.location || null, {
            transaction,
        });
        
        await sample_requests.setRequested_by( data.requested_by || null, {
            transaction,
        });
        
        await sample_requests.setProduct( data.product || null, {
            transaction,
        });
        

        

        

        return sample_requests;
    }
    

    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 sample_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sample_request_number: item.sample_request_number
            ||
            null
            ,
            
                sample_quantity: item.sample_quantity
            ||
            null
            ,
            
                requested_at: item.requested_at
            ||
            null
            ,
            
                needed_by: item.needed_by
            ||
            null
            ,
            
                sample_status: item.sample_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 sample_requests = await db.sample_requests.bulkCreate(sample_requestsData, { transaction });

        // For each item created, replace relation files
        

        return sample_requests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.sample_request_number !== undefined) updatePayload.sample_request_number = data.sample_request_number;
        
        
        if (data.sample_quantity !== undefined) updatePayload.sample_quantity = data.sample_quantity;
        
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.needed_by !== undefined) updatePayload.needed_by = data.needed_by;
        
        
        if (data.sample_status !== undefined) updatePayload.sample_status = data.sample_status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.account !== undefined) {
            await sample_requests.setAccount(
              
              data.account,
              
              { transaction }
            );
        }
        
        if (data.location !== undefined) {
            await sample_requests.setLocation(
              
              data.location,
              
              { transaction }
            );
        }
        
        if (data.requested_by !== undefined) {
            await sample_requests.setRequested_by(
              
              data.requested_by,
              
              { transaction }
            );
        }
        
        if (data.product !== undefined) {
            await sample_requests.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        

        
        

        

        return sample_requests;
    }

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

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

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


        return sample_requests;
    }

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

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

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

        await sample_requests.destroy({
            transaction
        });

        return sample_requests;
    }

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

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

        if (!sample_requests) {
            return sample_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.account = await sample_requests.getAccount({
            transaction
        });
        
        
        output.location = await sample_requests.getLocation({
            transaction
        });
        
        
        output.requested_by = await sample_requests.getRequested_by({
            transaction
        });
        
        
        output.product = await sample_requests.getProduct({
            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.accounts,
        as: 'account',
        
        where: filter.account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.account.split('|').map(term => Utils.uuid(term)) } },
            {
              account_name: {
                [Op.or]: filter.account.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)) } },
            {
              location_name: {
                [Op.or]: filter.location.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

            
            if (filter.sample_status) {
                where = {
                    ...where,
                sample_status: filter.sample_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.sample_requests.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(
                        'sample_requests',
                        'sample_request_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

