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

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

        const habits = await db.habits.create(
            {
                id: data.id || undefined,
        
        habit_name: data.habit_name
        ||
        null
            ,
            
        icon_name: data.icon_name
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        frequency_type: data.frequency_type
        ||
        null
            ,
            
        times_per_week: data.times_per_week
        ||
        null
            ,
            
        specific_days_csv: data.specific_days_csv
        ||
        null
            ,
            
        every_x_days: data.every_x_days
        ||
        null
            ,
            
        target_count_per_day: data.target_count_per_day
        ||
        null
            ,
            
        target_duration_minutes: data.target_duration_minutes
        ||
        null
            ,
            
        start_date: data.start_date
        ||
        null
            ,
            
        end_date: data.end_date
        ||
        null
            ,
            
        motivation: data.motivation
        ||
        null
            ,
            
        stacking_note: data.stacking_note
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return habits;
    }
    

    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 habitsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                habit_name: item.habit_name
            ||
            null
            ,
            
                icon_name: item.icon_name
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                frequency_type: item.frequency_type
            ||
            null
            ,
            
                times_per_week: item.times_per_week
            ||
            null
            ,
            
                specific_days_csv: item.specific_days_csv
            ||
            null
            ,
            
                every_x_days: item.every_x_days
            ||
            null
            ,
            
                target_count_per_day: item.target_count_per_day
            ||
            null
            ,
            
                target_duration_minutes: item.target_duration_minutes
            ||
            null
            ,
            
                start_date: item.start_date
            ||
            null
            ,
            
                end_date: item.end_date
            ||
            null
            ,
            
                motivation: item.motivation
            ||
            null
            ,
            
                stacking_note: item.stacking_note
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return habits;
    }

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

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


        

        const updatePayload = {};
        
        if (data.habit_name !== undefined) updatePayload.habit_name = data.habit_name;
        
        
        if (data.icon_name !== undefined) updatePayload.icon_name = data.icon_name;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.frequency_type !== undefined) updatePayload.frequency_type = data.frequency_type;
        
        
        if (data.times_per_week !== undefined) updatePayload.times_per_week = data.times_per_week;
        
        
        if (data.specific_days_csv !== undefined) updatePayload.specific_days_csv = data.specific_days_csv;
        
        
        if (data.every_x_days !== undefined) updatePayload.every_x_days = data.every_x_days;
        
        
        if (data.target_count_per_day !== undefined) updatePayload.target_count_per_day = data.target_count_per_day;
        
        
        if (data.target_duration_minutes !== undefined) updatePayload.target_duration_minutes = data.target_duration_minutes;
        
        
        if (data.start_date !== undefined) updatePayload.start_date = data.start_date;
        
        
        if (data.end_date !== undefined) updatePayload.end_date = data.end_date;
        
        
        if (data.motivation !== undefined) updatePayload.motivation = data.motivation;
        
        
        if (data.stacking_note !== undefined) updatePayload.stacking_note = data.stacking_note;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return habits;
    }

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

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

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


        return habits;
    }

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

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

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

        await habits.destroy({
            transaction
        });

        return habits;
    }

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

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

        if (!habits) {
            return habits;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.habit_logs_habit = await habits.getHabit_logs_habit({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await habits.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.habit_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'habits',
                        'habit_name',
                        filter.habit_name,
                    ),
                };
            }
            
            if (filter.icon_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'habits',
                        'icon_name',
                        filter.icon_name,
                    ),
                };
            }
            
            if (filter.specific_days_csv) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'habits',
                        'specific_days_csv',
                        filter.specific_days_csv,
                    ),
                };
            }
            
            if (filter.motivation) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'habits',
                        'motivation',
                        filter.motivation,
                    ),
                };
            }
            
            if (filter.stacking_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'habits',
                        'stacking_note',
                        filter.stacking_note,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    target_duration_minutes: {
                    ...where.target_duration_minutes,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.end_dateRange) {
                const [start, end] = filter.end_dateRange;

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

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

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

            
            if (filter.category) {
                where = {
                    ...where,
                category: filter.category,
            };
            }
            
            if (filter.frequency_type) {
                where = {
                    ...where,
                frequency_type: filter.frequency_type,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      



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

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

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

    
};

