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

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

        const kick_counts = await db.kick_counts.create(
            {
                id: data.id || undefined,
        
        session_start: data.session_start
        ||
        null
            ,
            
        session_end: data.session_end
        ||
        null
            ,
            
        kicks_count: data.kicks_count
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return kick_counts;
    }
    

    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 kick_countsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                session_start: item.session_start
            ||
            null
            ,
            
                session_end: item.session_end
            ||
            null
            ,
            
                kicks_count: item.kicks_count
            ||
            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 kick_counts = await db.kick_counts.bulkCreate(kick_countsData, { transaction });

        // For each item created, replace relation files
        

        return kick_counts;
    }

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

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


        

        const updatePayload = {};
        
        if (data.session_start !== undefined) updatePayload.session_start = data.session_start;
        
        
        if (data.session_end !== undefined) updatePayload.session_end = data.session_end;
        
        
        if (data.kicks_count !== undefined) updatePayload.kicks_count = data.kicks_count;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return kick_counts;
    }

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

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

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


        return kick_counts;
    }

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

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

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

        await kick_counts.destroy({
            transaction
        });

        return kick_counts;
    }

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

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

        if (!kick_counts) {
            return kick_counts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.pregnancy = await kick_counts.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(
                        'kick_counts',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

    
};

