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

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

        const world_calendar_days = await db.world_calendar_days.create(
            {
                id: data.id || undefined,
        
        day_start_at: data.day_start_at
        ||
        null
            ,
            
        day_end_at: data.day_end_at
        ||
        null
            ,
            
        season: data.season
        ||
        null
            ,
            
        tourism_index: data.tourism_index
        ||
        null
            ,
            
        inflation_index: data.inflation_index
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await world_calendar_days.setWeather_state( data.weather_state || null, {
            transaction,
        });
        

        

        

        return world_calendar_days;
    }
    

    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 world_calendar_daysData = data.map((item, index) => ({
                id: item.id || undefined,
                
                day_start_at: item.day_start_at
            ||
            null
            ,
            
                day_end_at: item.day_end_at
            ||
            null
            ,
            
                season: item.season
            ||
            null
            ,
            
                tourism_index: item.tourism_index
            ||
            null
            ,
            
                inflation_index: item.inflation_index
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return world_calendar_days;
    }

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

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


        

        const updatePayload = {};
        
        if (data.day_start_at !== undefined) updatePayload.day_start_at = data.day_start_at;
        
        
        if (data.day_end_at !== undefined) updatePayload.day_end_at = data.day_end_at;
        
        
        if (data.season !== undefined) updatePayload.season = data.season;
        
        
        if (data.tourism_index !== undefined) updatePayload.tourism_index = data.tourism_index;
        
        
        if (data.inflation_index !== undefined) updatePayload.inflation_index = data.inflation_index;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.weather_state !== undefined) {
            await world_calendar_days.setWeather_state(
              
              data.weather_state,
              
              { transaction }
            );
        }
        

        
        

        

        return world_calendar_days;
    }

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

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

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


        return world_calendar_days;
    }

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

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

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

        await world_calendar_days.destroy({
            transaction
        });

        return world_calendar_days;
    }

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

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

        if (!world_calendar_days) {
            return world_calendar_days;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.price_modifiers_calendar_day = await world_calendar_days.getPrice_modifiers_calendar_day({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.weather_state = await world_calendar_days.getWeather_state({
            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.weather_states,
        as: 'weather_state',
        
        where: filter.weather_state ? {
          [Op.or]: [
            { id: { [Op.in]: filter.weather_state.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.weather_state.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            

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

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

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

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

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

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

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

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

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

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

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

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


      



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

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

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

    
};

