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

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

        const contraction_sessions = await db.contraction_sessions.create(
            {
                id: data.id || undefined,
        
        labour_start: data.labour_start
        ||
        null
            ,
            
        labour_end: data.labour_end
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await contraction_sessions.setPregnancy( data.pregnancy || null, {
            transaction,
        });
        

        

        

        return contraction_sessions;
    }
    

    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 contraction_sessionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                labour_start: item.labour_start
            ||
            null
            ,
            
                labour_end: item.labour_end
            ||
            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 contraction_sessions = await db.contraction_sessions.bulkCreate(contraction_sessionsData, { transaction });

        // For each item created, replace relation files
        

        return contraction_sessions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.labour_start !== undefined) updatePayload.labour_start = data.labour_start;
        
        
        if (data.labour_end !== undefined) updatePayload.labour_end = data.labour_end;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.pregnancy !== undefined) {
            await contraction_sessions.setPregnancy(
              
              data.pregnancy,
              
              { transaction }
            );
        }
        

        
        

        

        return contraction_sessions;
    }

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

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

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


        return contraction_sessions;
    }

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

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

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

        await contraction_sessions.destroy({
            transaction
        });

        return contraction_sessions;
    }

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

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

        if (!contraction_sessions) {
            return contraction_sessions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.contractions_contraction_session = await contraction_sessions.getContractions_contraction_session({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.pregnancy = await contraction_sessions.getPregnancy({
            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.pregnancies,
        as: 'pregnancy',
        
        where: filter.pregnancy ? {
          [Op.or]: [
            { id: { [Op.in]: filter.pregnancy.split('|').map(term => Utils.uuid(term)) } },
            {
              notes: {
                [Op.or]: filter.pregnancy.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(
                        'contraction_sessions',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

        const records = await db.contraction_sessions.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,
        }));
    }

    
};

