
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,
        
        requested_at: data.requested_at
        ||
        null
            ,
            
        approved_at: data.approved_at
        ||
        null
            ,
            
        dispatched_at: data.dispatched_at
        ||
        null
            ,
            
        delivered_at: data.delivered_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        dispatch_note: data.dispatch_note
        ||
        null
            ,
            
        destination_address: data.destination_address
        ||
        null
            ,
            
        destination_latitude: data.destination_latitude
        ||
        null
            ,
            
        destination_longitude: data.destination_longitude
        ||
        null
            ,
            
        tracking_reference: data.tracking_reference
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medicine_dispatches.setRequested_by_rural_doctor( data.requested_by_rural_doctor || null, {
            transaction,
        });
        
        await medicine_dispatches.setApproved_by_admin( data.approved_by_admin || null, {
            transaction,
        });
        
        await medicine_dispatches.setCoordinated_by_city_doctor( data.coordinated_by_city_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,
                
                requested_at: item.requested_at
            ||
            null
            ,
            
                approved_at: item.approved_at
            ||
            null
            ,
            
                dispatched_at: item.dispatched_at
            ||
            null
            ,
            
                delivered_at: item.delivered_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                dispatch_note: item.dispatch_note
            ||
            null
            ,
            
                destination_address: item.destination_address
            ||
            null
            ,
            
                destination_latitude: item.destination_latitude
            ||
            null
            ,
            
                destination_longitude: item.destination_longitude
            ||
            null
            ,
            
                tracking_reference: item.tracking_reference
            ||
            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 medicine_dispatches = await db.medicine_dispatches.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.requested_at !== undefined) updatePayload.requested_at = data.requested_at;
        
        
        if (data.approved_at !== undefined) updatePayload.approved_at = data.approved_at;
        
        
        if (data.dispatched_at !== undefined) updatePayload.dispatched_at = data.dispatched_at;
        
        
        if (data.delivered_at !== undefined) updatePayload.delivered_at = data.delivered_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.dispatch_note !== undefined) updatePayload.dispatch_note = data.dispatch_note;
        
        
        if (data.destination_address !== undefined) updatePayload.destination_address = data.destination_address;
        
        
        if (data.destination_latitude !== undefined) updatePayload.destination_latitude = data.destination_latitude;
        
        
        if (data.destination_longitude !== undefined) updatePayload.destination_longitude = data.destination_longitude;
        
        
        if (data.tracking_reference !== undefined) updatePayload.tracking_reference = data.tracking_reference;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.requested_by_rural_doctor !== undefined) {
            await medicine_dispatches.setRequested_by_rural_doctor(
              
              data.requested_by_rural_doctor,
              
              { transaction }
            );
        }
        
        if (data.approved_by_admin !== undefined) {
            await medicine_dispatches.setApproved_by_admin(
              
              data.approved_by_admin,
              
              { transaction }
            );
        }
        
        if (data.coordinated_by_city_doctor !== undefined) {
            await medicine_dispatches.setCoordinated_by_city_doctor(
              
              data.coordinated_by_city_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.dispatch_items_medicine_dispatch = await medicine_dispatches.getDispatch_items_medicine_dispatch({
            transaction
        });
        
        
        
        
        
        
        
        
        output.truck_tracking_events_medicine_dispatch = await medicine_dispatches.getTruck_tracking_events_medicine_dispatch({
            transaction
        });
        
        
        
        
        
        
        
        
        output.requested_by_rural_doctor = await medicine_dispatches.getRequested_by_rural_doctor({
            transaction
        });
        
        
        output.approved_by_admin = await medicine_dispatches.getApproved_by_admin({
            transaction
        });
        
        
        output.coordinated_by_city_doctor = await medicine_dispatches.getCoordinated_by_city_doctor({
            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.rural_doctors,
        as: 'requested_by_rural_doctor',
        
        where: filter.requested_by_rural_doctor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.requested_by_rural_doctor.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.requested_by_rural_doctor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

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

            
            

            
            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.approved_atRange) {
                const [start, end] = filter.approved_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    approved_at: {
                    ...where.approved_at,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.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.destination_latitudeRange) {
                const [start, end] = filter.destination_latitudeRange;

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.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.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, ) {
        let where = {};
        
        

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

    
};

