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

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

        const semen_analyses = await db.semen_analyses.create(
            {
                id: data.id || undefined,
        
        test_date: data.test_date
        ||
        null
            ,
            
        volume_ml: data.volume_ml
        ||
        null
            ,
            
        concentration_million_per_ml: data.concentration_million_per_ml
        ||
        null
            ,
            
        motility_percent: data.motility_percent
        ||
        null
            ,
            
        morphology_percent: data.morphology_percent
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await semen_analyses.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return semen_analyses;
    }
    

    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 semen_analysesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                test_date: item.test_date
            ||
            null
            ,
            
                volume_ml: item.volume_ml
            ||
            null
            ,
            
                concentration_million_per_ml: item.concentration_million_per_ml
            ||
            null
            ,
            
                motility_percent: item.motility_percent
            ||
            null
            ,
            
                morphology_percent: item.morphology_percent
            ||
            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 semen_analyses = await db.semen_analyses.bulkCreate(semen_analysesData, { transaction });

        // For each item created, replace relation files
        

        return semen_analyses;
    }

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

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


        

        const updatePayload = {};
        
        if (data.test_date !== undefined) updatePayload.test_date = data.test_date;
        
        
        if (data.volume_ml !== undefined) updatePayload.volume_ml = data.volume_ml;
        
        
        if (data.concentration_million_per_ml !== undefined) updatePayload.concentration_million_per_ml = data.concentration_million_per_ml;
        
        
        if (data.motility_percent !== undefined) updatePayload.motility_percent = data.motility_percent;
        
        
        if (data.morphology_percent !== undefined) updatePayload.morphology_percent = data.morphology_percent;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await semen_analyses.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return semen_analyses;
    }

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

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

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


        return semen_analyses;
    }

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

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

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

        await semen_analyses.destroy({
            transaction
        });

        return semen_analyses;
    }

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

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

        if (!semen_analyses) {
            return semen_analyses;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await semen_analyses.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      



            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.semen_analyses.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(
                        'semen_analyses',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

