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

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

        const medical_camps = await db.medical_camps.create(
            {
                id: data.id || undefined,
        
        camp_name: data.camp_name
        ||
        null
            ,
            
        camp_type: data.camp_type
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        location_label: data.location_label
        ||
        null
            ,
            
        address_line: data.address_line
        ||
        null
            ,
            
        latitude: data.latitude
        ||
        null
            ,
            
        longitude: data.longitude
        ||
        null
            ,
            
        camp_status: data.camp_status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medical_camps.setOrganizer_organization( data.organizer_organization || null, {
            transaction,
        });
        
        await medical_camps.setCamp_lead_doctor( data.camp_lead_doctor || null, {
            transaction,
        });
        

        

        

        return medical_camps;
    }
    

    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 medical_campsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                camp_name: item.camp_name
            ||
            null
            ,
            
                camp_type: item.camp_type
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                location_label: item.location_label
            ||
            null
            ,
            
                address_line: item.address_line
            ||
            null
            ,
            
                latitude: item.latitude
            ||
            null
            ,
            
                longitude: item.longitude
            ||
            null
            ,
            
                camp_status: item.camp_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 medical_camps = await db.medical_camps.bulkCreate(medical_campsData, { transaction });

        // For each item created, replace relation files
        

        return medical_camps;
    }

    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 medical_camps = await db.medical_camps.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.camp_name !== undefined) updatePayload.camp_name = data.camp_name;
        
        
        if (data.camp_type !== undefined) updatePayload.camp_type = data.camp_type;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.location_label !== undefined) updatePayload.location_label = data.location_label;
        
        
        if (data.address_line !== undefined) updatePayload.address_line = data.address_line;
        
        
        if (data.latitude !== undefined) updatePayload.latitude = data.latitude;
        
        
        if (data.longitude !== undefined) updatePayload.longitude = data.longitude;
        
        
        if (data.camp_status !== undefined) updatePayload.camp_status = data.camp_status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organizer_organization !== undefined) {
            await medical_camps.setOrganizer_organization(
              
              data.organizer_organization,
              
              { transaction }
            );
        }
        
        if (data.camp_lead_doctor !== undefined) {
            await medical_camps.setCamp_lead_doctor(
              
              data.camp_lead_doctor,
              
              { transaction }
            );
        }
        

        
        

        

        return medical_camps;
    }

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

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

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


        return medical_camps;
    }

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

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

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

        await medical_camps.destroy({
            transaction
        });

        return medical_camps;
    }

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

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

        if (!medical_camps) {
            return medical_camps;
        }

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

        
        
        
        
        
        
        output.patient_profiles_registered_at_camp = await medical_camps.getPatient_profiles_registered_at_camp({
            transaction
        });
        
        
        
        output.appointments_camp = await medical_camps.getAppointments_camp({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.patient_vaccinations_administered_at_camp = await medical_camps.getPatient_vaccinations_administered_at_camp({
            transaction
        });
        
        
        
        
        
        
        
        output.feedbacks_camp = await medical_camps.getFeedbacks_camp({
            transaction
        });
        
        
        
        output.organizer_organization = await medical_camps.getOrganizer_organization({
            transaction
        });
        
        
        output.camp_lead_doctor = await medical_camps.getCamp_lead_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.organizations,
        as: 'organizer_organization',
        
      },

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



    ];

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

        where = {
          ...where,
          organizer_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.medical_camps.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(
                        'medical_camps',
                        'camp_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

