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

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

        const pregnancies = await db.pregnancies.create(
            {
                id: data.id || undefined,
        
        last_menstrual_period_date: data.last_menstrual_period_date
        ||
        null
            ,
            
        conception_date: data.conception_date
        ||
        null
            ,
            
        due_date: data.due_date
        ||
        null
            ,
            
        delivery_date: data.delivery_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        birth_plan: data.birth_plan
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await pregnancies.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return pregnancies;
    }
    

    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 pregnanciesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                last_menstrual_period_date: item.last_menstrual_period_date
            ||
            null
            ,
            
                conception_date: item.conception_date
            ||
            null
            ,
            
                due_date: item.due_date
            ||
            null
            ,
            
                delivery_date: item.delivery_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                birth_plan: item.birth_plan
            ||
            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 pregnancies = await db.pregnancies.bulkCreate(pregnanciesData, { transaction });

        // For each item created, replace relation files
        

        return pregnancies;
    }

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

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


        

        const updatePayload = {};
        
        if (data.last_menstrual_period_date !== undefined) updatePayload.last_menstrual_period_date = data.last_menstrual_period_date;
        
        
        if (data.conception_date !== undefined) updatePayload.conception_date = data.conception_date;
        
        
        if (data.due_date !== undefined) updatePayload.due_date = data.due_date;
        
        
        if (data.delivery_date !== undefined) updatePayload.delivery_date = data.delivery_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.birth_plan !== undefined) updatePayload.birth_plan = data.birth_plan;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await pregnancies.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

        

        return pregnancies;
    }

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

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

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


        return pregnancies;
    }

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

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

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

        await pregnancies.destroy({
            transaction
        });

        return pregnancies;
    }

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

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

        if (!pregnancies) {
            return pregnancies;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.pregnancy_symptom_logs_pregnancy = await pregnancies.getPregnancy_symptom_logs_pregnancy({
            transaction
        });
        
        
        output.breastfeeding_logs_pregnancy = await pregnancies.getBreastfeeding_logs_pregnancy({
            transaction
        });
        
        
        output.formula_feeding_logs_pregnancy = await pregnancies.getFormula_feeding_logs_pregnancy({
            transaction
        });
        
        
        output.baby_metrics_pregnancy = await pregnancies.getBaby_metrics_pregnancy({
            transaction
        });
        
        
        output.epds_assessments_pregnancy = await pregnancies.getEpds_assessments_pregnancy({
            transaction
        });
        
        
        output.kick_counts_pregnancy = await pregnancies.getKick_counts_pregnancy({
            transaction
        });
        
        
        output.contraction_sessions_pregnancy = await pregnancies.getContraction_sessions_pregnancy({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await pregnancies.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.birth_plan) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pregnancies',
                        'birth_plan',
                        filter.birth_plan,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'pregnancies',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

    
};

