
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
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        location_name: data.location_name
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        latitude: data.latitude
        ||
        null
            ,
            
        longitude: data.longitude
        ||
        null
            ,
            
        expected_attendees: data.expected_attendees
        ||
        null
            ,
            
        actual_attendees: data.actual_attendees
        ||
        null
            ,
            
        services_offered: data.services_offered
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medical_camps.setCreated_by_admin( data.created_by_admin || null, {
            transaction,
        });
        
        await medical_camps.setLead_city_doctor( data.lead_city_doctor || null, {
            transaction,
        });
        
        await medical_camps.setLead_rural_doctor( data.lead_rural_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
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                location_name: item.location_name
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                latitude: item.latitude
            ||
            null
            ,
            
                longitude: item.longitude
            ||
            null
            ,
            
                expected_attendees: item.expected_attendees
            ||
            null
            ,
            
                actual_attendees: item.actual_attendees
            ||
            null
            ,
            
                services_offered: item.services_offered
            ||
            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 medical_camps = await db.medical_camps.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.camp_name !== undefined) updatePayload.camp_name = data.camp_name;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.location_name !== undefined) updatePayload.location_name = data.location_name;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.latitude !== undefined) updatePayload.latitude = data.latitude;
        
        
        if (data.longitude !== undefined) updatePayload.longitude = data.longitude;
        
        
        if (data.expected_attendees !== undefined) updatePayload.expected_attendees = data.expected_attendees;
        
        
        if (data.actual_attendees !== undefined) updatePayload.actual_attendees = data.actual_attendees;
        
        
        if (data.services_offered !== undefined) updatePayload.services_offered = data.services_offered;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.created_by_admin !== undefined) {
            await medical_camps.setCreated_by_admin(
              
              data.created_by_admin,
              
              { transaction }
            );
        }
        
        if (data.lead_city_doctor !== undefined) {
            await medical_camps.setLead_city_doctor(
              
              data.lead_city_doctor,
              
              { transaction }
            );
        }
        
        if (data.lead_rural_doctor !== undefined) {
            await medical_camps.setLead_rural_doctor(
              
              data.lead_rural_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.appointments_medical_camp = await medical_camps.getAppointments_medical_camp({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.created_by_admin = await medical_camps.getCreated_by_admin({
            transaction
        });
        
        
        output.lead_city_doctor = await medical_camps.getLead_city_doctor({
            transaction
        });
        
        
        output.lead_rural_doctor = await medical_camps.getLead_rural_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.admins,
        as: 'created_by_admin',
        
        where: filter.created_by_admin ? {
          [Op.or]: [
            { id: { [Op.in]: filter.created_by_admin.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.created_by_admin.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.rural_doctors,
        as: 'lead_rural_doctor',
        
        where: filter.lead_rural_doctor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.lead_rural_doctor.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.lead_rural_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_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_camps',
                        'location_name',
                        filter.location_name,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_camps',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.services_offered) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_camps',
                        'services_offered',
                        filter.services_offered,
                    ),
                };
            }
            
            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.expected_attendeesRange) {
                const [start, end] = filter.expected_attendeesRange;

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    actual_attendees: {
                    ...where.actual_attendees,
                            [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.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, ) {
        let where = {};
        
        

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

    
};

