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

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

        const hotels = await db.hotels.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        legal_name: data.legal_name
        ||
        null
            ,
            
        address_line1: data.address_line1
        ||
        null
            ,
            
        address_line2: data.address_line2
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        state_region: data.state_region
        ||
        null
            ,
            
        postal_code: data.postal_code
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        website: data.website
        ||
        null
            ,
            
        timezone: data.timezone
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        default_tax_rate: data.default_tax_rate
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
        stripe_customer_reference: data.stripe_customer_reference
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await hotels.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return hotels;
    }
    

    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 hotelsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                legal_name: item.legal_name
            ||
            null
            ,
            
                address_line1: item.address_line1
            ||
            null
            ,
            
                address_line2: item.address_line2
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                state_region: item.state_region
            ||
            null
            ,
            
                postal_code: item.postal_code
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                website: item.website
            ||
            null
            ,
            
                timezone: item.timezone
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                default_tax_rate: item.default_tax_rate
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
                stripe_customer_reference: item.stripe_customer_reference
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return hotels;
    }

    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 hotels = await db.hotels.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.legal_name !== undefined) updatePayload.legal_name = data.legal_name;
        
        
        if (data.address_line1 !== undefined) updatePayload.address_line1 = data.address_line1;
        
        
        if (data.address_line2 !== undefined) updatePayload.address_line2 = data.address_line2;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.state_region !== undefined) updatePayload.state_region = data.state_region;
        
        
        if (data.postal_code !== undefined) updatePayload.postal_code = data.postal_code;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.website !== undefined) updatePayload.website = data.website;
        
        
        if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.default_tax_rate !== undefined) updatePayload.default_tax_rate = data.default_tax_rate;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        if (data.stripe_customer_reference !== undefined) updatePayload.stripe_customer_reference = data.stripe_customer_reference;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return hotels;
    }

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

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

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


        return hotels;
    }

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

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

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

        await hotels.destroy({
            transaction
        });

        return hotels;
    }

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

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

        if (!hotels) {
            return hotels;
        }

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

        
        
        
        
        
        
        output.departments_hotel = await hotels.getDepartments_hotel({
            transaction
        });
        
        
        output.staff_profiles_hotel = await hotels.getStaff_profiles_hotel({
            transaction
        });
        
        
        output.shifts_hotel = await hotels.getShifts_hotel({
            transaction
        });
        
        
        output.room_types_hotel = await hotels.getRoom_types_hotel({
            transaction
        });
        
        
        output.rooms_hotel = await hotels.getRooms_hotel({
            transaction
        });
        
        
        output.guests_hotel = await hotels.getGuests_hotel({
            transaction
        });
        
        
        output.guest_documents_hotel = await hotels.getGuest_documents_hotel({
            transaction
        });
        
        
        output.rate_plans_hotel = await hotels.getRate_plans_hotel({
            transaction
        });
        
        
        output.seasonal_rates_hotel = await hotels.getSeasonal_rates_hotel({
            transaction
        });
        
        
        output.dynamic_pricing_rules_hotel = await hotels.getDynamic_pricing_rules_hotel({
            transaction
        });
        
        
        output.sales_channels_hotel = await hotels.getSales_channels_hotel({
            transaction
        });
        
        
        output.ota_connections_hotel = await hotels.getOta_connections_hotel({
            transaction
        });
        
        
        output.reservations_hotel = await hotels.getReservations_hotel({
            transaction
        });
        
        
        output.reservation_guests_hotel = await hotels.getReservation_guests_hotel({
            transaction
        });
        
        
        output.stay_folios_hotel = await hotels.getStay_folios_hotel({
            transaction
        });
        
        
        output.folio_items_hotel = await hotels.getFolio_items_hotel({
            transaction
        });
        
        
        output.payments_hotel = await hotels.getPayments_hotel({
            transaction
        });
        
        
        output.refunds_hotel = await hotels.getRefunds_hotel({
            transaction
        });
        
        
        output.invoices_hotel = await hotels.getInvoices_hotel({
            transaction
        });
        
        
        output.housekeeping_tasks_hotel = await hotels.getHousekeeping_tasks_hotel({
            transaction
        });
        
        
        output.maintenance_tickets_hotel = await hotels.getMaintenance_tickets_hotel({
            transaction
        });
        
        
        output.notifications_hotel = await hotels.getNotifications_hotel({
            transaction
        });
        
        
        output.booking_widgets_hotel = await hotels.getBooking_widgets_hotel({
            transaction
        });
        
        
        output.subscriptions_hotel = await hotels.getSubscriptions_hotel({
            transaction
        });
        
        
        output.audit_logs_hotel = await hotels.getAudit_logs_hotel({
            transaction
        });
        
        
        output.daily_snapshots_hotel = await hotels.getDaily_snapshots_hotel({
            transaction
        });
        
        
        
        output.organizations = await hotels.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.legal_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'legal_name',
                        filter.legal_name,
                    ),
                };
            }
            
            if (filter.address_line1) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'address_line1',
                        filter.address_line1,
                    ),
                };
            }
            
            if (filter.address_line2) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'address_line2',
                        filter.address_line2,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.state_region) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'state_region',
                        filter.state_region,
                    ),
                };
            }
            
            if (filter.postal_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'postal_code',
                        filter.postal_code,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.website) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'website',
                        filter.website,
                    ),
                };
            }
            
            if (filter.timezone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'timezone',
                        filter.timezone,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.stripe_customer_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'hotels',
                        'stripe_customer_reference',
                        filter.stripe_customer_reference,
                    ),
                };
            }
            

            
            

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

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

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

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

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


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

        const records = await db.hotels.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,
        }));
    }

    
};

