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

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

        const holidays = await db.holidays.create(
            {
                id: data.id || undefined,
        
        holidayDate: data.holidayDate
        ||
        null
            ,
            
        holidayName: data.holidayName
        ||
        null
            ,
            
        holidayType: data.holidayType
        ||
        null
            ,
            
        year: data.year
        ||
        null
            ,
            
        isRecurring: data.isRecurring
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return holidays;
    }
    

    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 holidaysData = data.map((item, index) => ({
                id: item.id || undefined,
                
                holidayDate: item.holidayDate
            ||
            null
            ,
            
                holidayName: item.holidayName
            ||
            null
            ,
            
                holidayType: item.holidayType
            ||
            null
            ,
            
                year: item.year
            ||
            null
            ,
            
                isRecurring: item.isRecurring
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return holidays;
    }

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

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


        

        const updatePayload = {};
        
        if (data.holidayDate !== undefined) updatePayload.holidayDate = data.holidayDate;
        
        
        if (data.holidayName !== undefined) updatePayload.holidayName = data.holidayName;
        
        
        if (data.holidayType !== undefined) updatePayload.holidayType = data.holidayType;
        
        
        if (data.year !== undefined) updatePayload.year = data.year;
        
        
        if (data.isRecurring !== undefined) updatePayload.isRecurring = data.isRecurring;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return holidays;
    }

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

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

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


        return holidays;
    }

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

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

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

        await holidays.destroy({
            transaction
        });

        return holidays;
    }

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

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

        if (!holidays) {
            return holidays;
        }

        const output = holidays.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.holidayName) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'holidays',
                        'holidayName',
                        filter.holidayName,
                    ),
                };
            }
            

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

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

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

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

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

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

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

            
            if (filter.holidayType) {
                where = {
                    ...where,
                holidayType: filter.holidayType,
            };
            }
            
            if (filter.isRecurring) {
                where = {
                    ...where,
                isRecurring: filter.isRecurring,
            };
            }
            




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

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

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

    
};

