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

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

        const medicine_dispatches = await db.medicine_dispatches.create(
            {
                id: data.id || undefined,
        
        dispatched_at: data.dispatched_at
        ||
        null
            ,
            
        expected_delivery_at: data.expected_delivery_at
        ||
        null
            ,
            
        delivered_at: data.delivered_at
        ||
        null
            ,
            
        dispatch_status: data.dispatch_status
        ||
        null
            ,
            
        tracking_reference: data.tracking_reference
        ||
        null
            ,
            
        last_known_latitude: data.last_known_latitude
        ||
        null
            ,
            
        last_known_longitude: data.last_known_longitude
        ||
        null
            ,
            
        delivery_notes: data.delivery_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medicine_dispatches.setPrescription( data.prescription || null, {
            transaction,
        });
        
        await medicine_dispatches.setFrom_organization( data.from_organization || null, {
            transaction,
        });
        
        await medicine_dispatches.setTo_patient( data.to_patient || null, {
            transaction,
        });
        
        await medicine_dispatches.setTo_organization( data.to_organization || null, {
            transaction,
        });
        
        await medicine_dispatches.setDispatched_by_doctor( data.dispatched_by_doctor || null, {
            transaction,
        });
        

        

        

        return medicine_dispatches;
    }
    

    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 medicine_dispatchesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                dispatched_at: item.dispatched_at
            ||
            null
            ,
            
                expected_delivery_at: item.expected_delivery_at
            ||
            null
            ,
            
                delivered_at: item.delivered_at
            ||
            null
            ,
            
                dispatch_status: item.dispatch_status
            ||
            null
            ,
            
                tracking_reference: item.tracking_reference
            ||
            null
            ,
            
                last_known_latitude: item.last_known_latitude
            ||
            null
            ,
            
                last_known_longitude: item.last_known_longitude
            ||
            null
            ,
            
                delivery_notes: item.delivery_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const medicine_dispatches = await db.medicine_dispatches.bulkCreate(medicine_dispatchesData, { transaction });

        // For each item created, replace relation files
        

        return medicine_dispatches;
    }

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

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


        

        const updatePayload = {};
        
        if (data.dispatched_at !== undefined) updatePayload.dispatched_at = data.dispatched_at;
        
        
        if (data.expected_delivery_at !== undefined) updatePayload.expected_delivery_at = data.expected_delivery_at;
        
        
        if (data.delivered_at !== undefined) updatePayload.delivered_at = data.delivered_at;
        
        
        if (data.dispatch_status !== undefined) updatePayload.dispatch_status = data.dispatch_status;
        
        
        if (data.tracking_reference !== undefined) updatePayload.tracking_reference = data.tracking_reference;
        
        
        if (data.last_known_latitude !== undefined) updatePayload.last_known_latitude = data.last_known_latitude;
        
        
        if (data.last_known_longitude !== undefined) updatePayload.last_known_longitude = data.last_known_longitude;
        
        
        if (data.delivery_notes !== undefined) updatePayload.delivery_notes = data.delivery_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.prescription !== undefined) {
            await medicine_dispatches.setPrescription(
              
              data.prescription,
              
              { transaction }
            );
        }
        
        if (data.from_organization !== undefined) {
            await medicine_dispatches.setFrom_organization(
              
              data.from_organization,
              
              { transaction }
            );
        }
        
        if (data.to_patient !== undefined) {
            await medicine_dispatches.setTo_patient(
              
              data.to_patient,
              
              { transaction }
            );
        }
        
        if (data.to_organization !== undefined) {
            await medicine_dispatches.setTo_organization(
              
              data.to_organization,
              
              { transaction }
            );
        }
        
        if (data.dispatched_by_doctor !== undefined) {
            await medicine_dispatches.setDispatched_by_doctor(
              
              data.dispatched_by_doctor,
              
              { transaction }
            );
        }
        

        
        

        

        return medicine_dispatches;
    }

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

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

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


        return medicine_dispatches;
    }

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

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

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

        await medicine_dispatches.destroy({
            transaction
        });

        return medicine_dispatches;
    }

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

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

        if (!medicine_dispatches) {
            return medicine_dispatches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.prescription = await medicine_dispatches.getPrescription({
            transaction
        });
        
        
        output.from_organization = await medicine_dispatches.getFrom_organization({
            transaction
        });
        
        
        output.to_patient = await medicine_dispatches.getTo_patient({
            transaction
        });
        
        
        output.to_organization = await medicine_dispatches.getTo_organization({
            transaction
        });
        
        
        output.dispatched_by_doctor = await medicine_dispatches.getDispatched_by_doctor({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.organizations,
        as: 'from_organization',
        
      },

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

      {
        model: db.organizations,
        as: 'to_organization',
        
      },

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



    ];

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

            
            if (filter.tracking_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medicine_dispatches',
                        'tracking_reference',
                        filter.tracking_reference,
                    ),
                };
            }
            
            if (filter.delivery_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medicine_dispatches',
                        'delivery_notes',
                        filter.delivery_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.dispatch_status) {
                where = {
                    ...where,
                dispatch_status: filter.dispatch_status,
            };
            }
            


      

      
      if (filter.from_organization) {
        const listItems = filter.from_organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          from_organizationId: {[Op.or]: listItems}
        };
      }
      

      

      
      if (filter.to_organization) {
        const listItems = filter.to_organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          to_organizationId: {[Op.or]: listItems}
        };
      }
      

      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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.medicine_dispatches.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'medicine_dispatches',
                        'tracking_reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

