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

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

        const daily_seeds = await db.daily_seeds.create(
            {
                id: data.id || undefined,
        
        seed_key: data.seed_key
        ||
        null
            ,
            
        active_from: data.active_from
        ||
        null
            ,
            
        active_to: data.active_to
        ||
        null
            ,
            
        timer_profile: data.timer_profile
        ||
        null
            ,
            
        mode_selection: data.mode_selection
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return daily_seeds;
    }
    

    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 daily_seedsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                seed_key: item.seed_key
            ||
            null
            ,
            
                active_from: item.active_from
            ||
            null
            ,
            
                active_to: item.active_to
            ||
            null
            ,
            
                timer_profile: item.timer_profile
            ||
            null
            ,
            
                mode_selection: item.mode_selection
            ||
            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 daily_seeds = await db.daily_seeds.bulkCreate(daily_seedsData, { transaction });

        // For each item created, replace relation files
        

        return daily_seeds;
    }

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

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


        

        const updatePayload = {};
        
        if (data.seed_key !== undefined) updatePayload.seed_key = data.seed_key;
        
        
        if (data.active_from !== undefined) updatePayload.active_from = data.active_from;
        
        
        if (data.active_to !== undefined) updatePayload.active_to = data.active_to;
        
        
        if (data.timer_profile !== undefined) updatePayload.timer_profile = data.timer_profile;
        
        
        if (data.mode_selection !== undefined) updatePayload.mode_selection = data.mode_selection;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return daily_seeds;
    }

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

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

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


        return daily_seeds;
    }

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

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

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

        await daily_seeds.destroy({
            transaction
        });

        return daily_seeds;
    }

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

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

        if (!daily_seeds) {
            return daily_seeds;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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 = [



    ];

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

            
            if (filter.seed_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'daily_seeds',
                        'seed_key',
                        filter.seed_key,
                    ),
                };
            }
            

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

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

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

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

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

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

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

            
            if (filter.timer_profile) {
                where = {
                    ...where,
                timer_profile: filter.timer_profile,
            };
            }
            
            if (filter.mode_selection) {
                where = {
                    ...where,
                mode_selection: filter.mode_selection,
            };
            }
            
            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.daily_seeds.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(
                        'daily_seeds',
                        'seed_key',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

