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

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

        const contraception_logs = await db.contraception_logs.create(
            {
                id: data.id || undefined,
        
        method: data.method
        ||
        null
            ,
            
        start_date: data.start_date
        ||
        null
            ,
            
        renewal_due_date: data.renewal_due_date
        ||
        null
            ,
            
        daily_reminder_enabled: data.daily_reminder_enabled
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return contraception_logs;
    }
    

    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 contraception_logsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                method: item.method
            ||
            null
            ,
            
                start_date: item.start_date
            ||
            null
            ,
            
                renewal_due_date: item.renewal_due_date
            ||
            null
            ,
            
                daily_reminder_enabled: item.daily_reminder_enabled
            ||
            false
        
            ,
            
                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 contraception_logs = await db.contraception_logs.bulkCreate(contraception_logsData, { transaction });

        // For each item created, replace relation files
        

        return contraception_logs;
    }

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

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


        

        const updatePayload = {};
        
        if (data.method !== undefined) updatePayload.method = data.method;
        
        
        if (data.start_date !== undefined) updatePayload.start_date = data.start_date;
        
        
        if (data.renewal_due_date !== undefined) updatePayload.renewal_due_date = data.renewal_due_date;
        
        
        if (data.daily_reminder_enabled !== undefined) updatePayload.daily_reminder_enabled = data.daily_reminder_enabled;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return contraception_logs;
    }

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

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

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


        return contraception_logs;
    }

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

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

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

        await contraception_logs.destroy({
            transaction
        });

        return contraception_logs;
    }

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

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

        if (!contraception_logs) {
            return contraception_logs;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await contraception_logs.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.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'contraception_logs',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

            
            if (filter.method) {
                where = {
                    ...where,
                method: filter.method,
            };
            }
            
            if (filter.daily_reminder_enabled) {
                where = {
                    ...where,
                daily_reminder_enabled: filter.daily_reminder_enabled,
            };
            }
            


      



            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.contraception_logs.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(
                        'contraception_logs',
                        'method',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

