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

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

        const pregnancy_followups = await db.pregnancy_followups.create(
            {
                id: data.id || undefined,
        
        followup_number: data.followup_number
        ||
        null
            ,
            
        weight: data.weight
        ||
        null
            ,
            
        blood_pressure: data.blood_pressure
        ||
        null
            ,
            
        delivery_plan: data.delivery_plan
        ||
        null
            ,
            
        next_visit_date: data.next_visit_date
        ||
        null
            ,
            
        price: data.price
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await pregnancy_followups.setPatient( data.patient || null, {
            transaction,
        });
        

        

        

        return pregnancy_followups;
    }
    

    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 pregnancy_followupsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                followup_number: item.followup_number
            ||
            null
            ,
            
                weight: item.weight
            ||
            null
            ,
            
                blood_pressure: item.blood_pressure
            ||
            null
            ,
            
                delivery_plan: item.delivery_plan
            ||
            null
            ,
            
                next_visit_date: item.next_visit_date
            ||
            null
            ,
            
                price: item.price
            ||
            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 pregnancy_followups = await db.pregnancy_followups.bulkCreate(pregnancy_followupsData, { transaction });

        // For each item created, replace relation files
        

        return pregnancy_followups;
    }

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

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


        

        const updatePayload = {};
        
        if (data.followup_number !== undefined) updatePayload.followup_number = data.followup_number;
        
        
        if (data.weight !== undefined) updatePayload.weight = data.weight;
        
        
        if (data.blood_pressure !== undefined) updatePayload.blood_pressure = data.blood_pressure;
        
        
        if (data.delivery_plan !== undefined) updatePayload.delivery_plan = data.delivery_plan;
        
        
        if (data.next_visit_date !== undefined) updatePayload.next_visit_date = data.next_visit_date;
        
        
        if (data.price !== undefined) updatePayload.price = data.price;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await pregnancy_followups.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        

        
        

        

        return pregnancy_followups;
    }

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

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

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


        return pregnancy_followups;
    }

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

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

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

        await pregnancy_followups.destroy({
            transaction
        });

        return pregnancy_followups;
    }

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

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

        if (!pregnancy_followups) {
            return pregnancy_followups;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await pregnancy_followups.getPatient({
            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.patients,
        as: 'patient',
        
        where: filter.patient ? {
          [Op.or]: [
            { id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.followup_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pregnancy_followups',
                        'followup_number',
                        filter.followup_number,
                    ),
                };
            }
            
            if (filter.blood_pressure) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pregnancy_followups',
                        'blood_pressure',
                        filter.blood_pressure,
                    ),
                };
            }
            
            if (filter.delivery_plan) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pregnancy_followups',
                        'delivery_plan',
                        filter.delivery_plan,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pregnancy_followups',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

    
};

