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

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

        const weather_states = await db.weather_states.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        weather_type: data.weather_type
        ||
        null
            ,
            
        temperature_c: data.temperature_c
        ||
        null
            ,
            
        wind_speed: data.wind_speed
        ||
        null
            ,
            
        rain_intensity: data.rain_intensity
        ||
        null
            ,
            
        has_thunder: data.has_thunder
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return weather_states;
    }
    

    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 weather_statesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                weather_type: item.weather_type
            ||
            null
            ,
            
                temperature_c: item.temperature_c
            ||
            null
            ,
            
                wind_speed: item.wind_speed
            ||
            null
            ,
            
                rain_intensity: item.rain_intensity
            ||
            null
            ,
            
                has_thunder: item.has_thunder
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return weather_states;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.weather_type !== undefined) updatePayload.weather_type = data.weather_type;
        
        
        if (data.temperature_c !== undefined) updatePayload.temperature_c = data.temperature_c;
        
        
        if (data.wind_speed !== undefined) updatePayload.wind_speed = data.wind_speed;
        
        
        if (data.rain_intensity !== undefined) updatePayload.rain_intensity = data.rain_intensity;
        
        
        if (data.has_thunder !== undefined) updatePayload.has_thunder = data.has_thunder;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return weather_states;
    }

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

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

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


        return weather_states;
    }

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

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

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

        await weather_states.destroy({
            transaction
        });

        return weather_states;
    }

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

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

        if (!weather_states) {
            return weather_states;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.world_calendar_days_weather_state = await weather_states.getWorld_calendar_days_weather_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 = [



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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




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

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

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

    
};

