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

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

        const daily_snapshots = await db.daily_snapshots.create(
            {
                id: data.id || undefined,
        
        snapshot_at: data.snapshot_at
        ||
        null
            ,
            
        rooms_available: data.rooms_available
        ||
        null
            ,
            
        rooms_occupied: data.rooms_occupied
        ||
        null
            ,
            
        rooms_dirty: data.rooms_dirty
        ||
        null
            ,
            
        rooms_out_of_service: data.rooms_out_of_service
        ||
        null
            ,
            
        occupancy_rate_percent: data.occupancy_rate_percent
        ||
        null
            ,
            
        revenue_today: data.revenue_today
        ||
        null
            ,
            
        revenue_month_to_date: data.revenue_month_to_date
        ||
        null
            ,
            
        adr: data.adr
        ||
        null
            ,
            
        revpar: data.revpar
        ||
        null
            ,
            
        arrivals_today: data.arrivals_today
        ||
        null
            ,
            
        departures_today: data.departures_today
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await daily_snapshots.setHotel( data.hotel || null, {
            transaction,
        });
        
        await daily_snapshots.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return daily_snapshots;
    }
    

    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_snapshotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                snapshot_at: item.snapshot_at
            ||
            null
            ,
            
                rooms_available: item.rooms_available
            ||
            null
            ,
            
                rooms_occupied: item.rooms_occupied
            ||
            null
            ,
            
                rooms_dirty: item.rooms_dirty
            ||
            null
            ,
            
                rooms_out_of_service: item.rooms_out_of_service
            ||
            null
            ,
            
                occupancy_rate_percent: item.occupancy_rate_percent
            ||
            null
            ,
            
                revenue_today: item.revenue_today
            ||
            null
            ,
            
                revenue_month_to_date: item.revenue_month_to_date
            ||
            null
            ,
            
                adr: item.adr
            ||
            null
            ,
            
                revpar: item.revpar
            ||
            null
            ,
            
                arrivals_today: item.arrivals_today
            ||
            null
            ,
            
                departures_today: item.departures_today
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return daily_snapshots;
    }

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

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


        

        const updatePayload = {};
        
        if (data.snapshot_at !== undefined) updatePayload.snapshot_at = data.snapshot_at;
        
        
        if (data.rooms_available !== undefined) updatePayload.rooms_available = data.rooms_available;
        
        
        if (data.rooms_occupied !== undefined) updatePayload.rooms_occupied = data.rooms_occupied;
        
        
        if (data.rooms_dirty !== undefined) updatePayload.rooms_dirty = data.rooms_dirty;
        
        
        if (data.rooms_out_of_service !== undefined) updatePayload.rooms_out_of_service = data.rooms_out_of_service;
        
        
        if (data.occupancy_rate_percent !== undefined) updatePayload.occupancy_rate_percent = data.occupancy_rate_percent;
        
        
        if (data.revenue_today !== undefined) updatePayload.revenue_today = data.revenue_today;
        
        
        if (data.revenue_month_to_date !== undefined) updatePayload.revenue_month_to_date = data.revenue_month_to_date;
        
        
        if (data.adr !== undefined) updatePayload.adr = data.adr;
        
        
        if (data.revpar !== undefined) updatePayload.revpar = data.revpar;
        
        
        if (data.arrivals_today !== undefined) updatePayload.arrivals_today = data.arrivals_today;
        
        
        if (data.departures_today !== undefined) updatePayload.departures_today = data.departures_today;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.hotel !== undefined) {
            await daily_snapshots.setHotel(
              
              data.hotel,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await daily_snapshots.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return daily_snapshots;
    }

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

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

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


        return daily_snapshots;
    }

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

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

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

        await daily_snapshots.destroy({
            transaction
        });

        return daily_snapshots;
    }

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

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

        if (!daily_snapshots) {
            return daily_snapshots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.hotel = await daily_snapshots.getHotel({
            transaction
        });
        
        
        output.organizations = await daily_snapshots.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.hotels,
        as: 'hotel',
        
        where: filter.hotel ? {
          [Op.or]: [
            { id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        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_snapshots.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'daily_snapshots',
                        'snapshot_at',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

