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

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

        const vision_prescriptions = await db.vision_prescriptions.create(
            {
                id: data.id || undefined,
        
        prescription_date: data.prescription_date
        ||
        null
            ,
            
        right_sphere: data.right_sphere
        ||
        null
            ,
            
        right_cylinder: data.right_cylinder
        ||
        null
            ,
            
        right_axis: data.right_axis
        ||
        null
            ,
            
        left_sphere: data.left_sphere
        ||
        null
            ,
            
        left_cylinder: data.left_cylinder
        ||
        null
            ,
            
        left_axis: data.left_axis
        ||
        null
            ,
            
        add_power: data.add_power
        ||
        null
            ,
            
        pupillary_distance_mm: data.pupillary_distance_mm
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await vision_prescriptions.setUser( data.user || null, {
            transaction,
        });
        
        await vision_prescriptions.setOptometrist( data.optometrist || null, {
            transaction,
        });
        

        

        

        return vision_prescriptions;
    }
    

    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 vision_prescriptionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                prescription_date: item.prescription_date
            ||
            null
            ,
            
                right_sphere: item.right_sphere
            ||
            null
            ,
            
                right_cylinder: item.right_cylinder
            ||
            null
            ,
            
                right_axis: item.right_axis
            ||
            null
            ,
            
                left_sphere: item.left_sphere
            ||
            null
            ,
            
                left_cylinder: item.left_cylinder
            ||
            null
            ,
            
                left_axis: item.left_axis
            ||
            null
            ,
            
                add_power: item.add_power
            ||
            null
            ,
            
                pupillary_distance_mm: item.pupillary_distance_mm
            ||
            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 vision_prescriptions = await db.vision_prescriptions.bulkCreate(vision_prescriptionsData, { transaction });

        // For each item created, replace relation files
        

        return vision_prescriptions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.prescription_date !== undefined) updatePayload.prescription_date = data.prescription_date;
        
        
        if (data.right_sphere !== undefined) updatePayload.right_sphere = data.right_sphere;
        
        
        if (data.right_cylinder !== undefined) updatePayload.right_cylinder = data.right_cylinder;
        
        
        if (data.right_axis !== undefined) updatePayload.right_axis = data.right_axis;
        
        
        if (data.left_sphere !== undefined) updatePayload.left_sphere = data.left_sphere;
        
        
        if (data.left_cylinder !== undefined) updatePayload.left_cylinder = data.left_cylinder;
        
        
        if (data.left_axis !== undefined) updatePayload.left_axis = data.left_axis;
        
        
        if (data.add_power !== undefined) updatePayload.add_power = data.add_power;
        
        
        if (data.pupillary_distance_mm !== undefined) updatePayload.pupillary_distance_mm = data.pupillary_distance_mm;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return vision_prescriptions;
    }

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

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

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


        return vision_prescriptions;
    }

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

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

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

        await vision_prescriptions.destroy({
            transaction
        });

        return vision_prescriptions;
    }

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

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

        if (!vision_prescriptions) {
            return vision_prescriptions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await vision_prescriptions.getUser({
            transaction
        });
        
        
        output.optometrist = await vision_prescriptions.getOptometrist({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.healthcare_providers,
        as: 'optometrist',
        
        where: filter.optometrist ? {
          [Op.or]: [
            { id: { [Op.in]: filter.optometrist.split('|').map(term => Utils.uuid(term)) } },
            {
              provider_name: {
                [Op.or]: filter.optometrist.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(
                        'vision_prescriptions',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        const records = await db.vision_prescriptions.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,
        }));
    }

    
};

