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

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

        const contractions = await db.contractions.create(
            {
                id: data.id || undefined,
        
        contraction_start: data.contraction_start
        ||
        null
            ,
            
        contraction_end: data.contraction_end
        ||
        null
            ,
            
        duration_seconds: data.duration_seconds
        ||
        null
            ,
            
        interval_seconds: data.interval_seconds
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await contractions.setContraction_session( data.contraction_session || null, {
            transaction,
        });
        

        

        

        return contractions;
    }
    

    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 contractionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                contraction_start: item.contraction_start
            ||
            null
            ,
            
                contraction_end: item.contraction_end
            ||
            null
            ,
            
                duration_seconds: item.duration_seconds
            ||
            null
            ,
            
                interval_seconds: item.interval_seconds
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const contractions = await db.contractions.bulkCreate(contractionsData, { transaction });

        // For each item created, replace relation files
        

        return contractions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.contraction_start !== undefined) updatePayload.contraction_start = data.contraction_start;
        
        
        if (data.contraction_end !== undefined) updatePayload.contraction_end = data.contraction_end;
        
        
        if (data.duration_seconds !== undefined) updatePayload.duration_seconds = data.duration_seconds;
        
        
        if (data.interval_seconds !== undefined) updatePayload.interval_seconds = data.interval_seconds;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.contraction_session !== undefined) {
            await contractions.setContraction_session(
              
              data.contraction_session,
              
              { transaction }
            );
        }
        

        
        

        

        return contractions;
    }

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

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

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


        return contractions;
    }

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

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

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

        await contractions.destroy({
            transaction
        });

        return contractions;
    }

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

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

        if (!contractions) {
            return contractions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.contraction_session = await contractions.getContraction_session({
            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.contraction_sessions,
        as: 'contraction_session',
        
        where: filter.contraction_session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.contraction_session.split('|').map(term => Utils.uuid(term)) } },
            {
              notes: {
                [Op.or]: filter.contraction_session.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

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

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

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

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

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

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

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

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

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

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

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

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

    
};

