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

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

        const reading_streaks = await db.reading_streaks.create(
            {
                id: data.id || undefined,
        
        current_streak_days: data.current_streak_days
        ||
        null
            ,
            
        best_streak_days: data.best_streak_days
        ||
        null
            ,
            
        last_streak_date: data.last_streak_date
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return reading_streaks;
    }
    

    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 reading_streaksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                current_streak_days: item.current_streak_days
            ||
            null
            ,
            
                best_streak_days: item.best_streak_days
            ||
            null
            ,
            
                last_streak_date: item.last_streak_date
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return reading_streaks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.current_streak_days !== undefined) updatePayload.current_streak_days = data.current_streak_days;
        
        
        if (data.best_streak_days !== undefined) updatePayload.best_streak_days = data.best_streak_days;
        
        
        if (data.last_streak_date !== undefined) updatePayload.last_streak_date = data.last_streak_date;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return reading_streaks;
    }

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

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

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


        return reading_streaks;
    }

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

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

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

        await reading_streaks.destroy({
            transaction
        });

        return reading_streaks;
    }

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

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

        if (!reading_streaks) {
            return reading_streaks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await reading_streaks.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.current_streak_daysRange) {
                const [start, end] = filter.current_streak_daysRange;

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

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

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

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

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

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

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

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

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

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

    
};

