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

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

        const guests = await db.guests.create(
            {
                id: data.id || undefined,
        
        first_name: data.first_name
        ||
        null
            ,
            
        last_name: data.last_name
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        nationality: data.nationality
        ||
        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
            ,
            
        preferences: data.preferences
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        loyalty_points: data.loyalty_points
        ||
        null
            ,
            
        marketing_opt_in: data.marketing_opt_in
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return guests;
    }
    

    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 guestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                first_name: item.first_name
            ||
            null
            ,
            
                last_name: item.last_name
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                nationality: item.nationality
            ||
            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
            ,
            
                preferences: item.preferences
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                loyalty_points: item.loyalty_points
            ||
            null
            ,
            
                marketing_opt_in: item.marketing_opt_in
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return guests;
    }

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


        

        const updatePayload = {};
        
        if (data.first_name !== undefined) updatePayload.first_name = data.first_name;
        
        
        if (data.last_name !== undefined) updatePayload.last_name = data.last_name;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.nationality !== undefined) updatePayload.nationality = data.nationality;
        
        
        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.preferences !== undefined) updatePayload.preferences = data.preferences;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.loyalty_points !== undefined) updatePayload.loyalty_points = data.loyalty_points;
        
        
        if (data.marketing_opt_in !== undefined) updatePayload.marketing_opt_in = data.marketing_opt_in;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return guests;
    }

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

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

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


        return guests;
    }

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

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

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

        await guests.destroy({
            transaction
        });

        return guests;
    }

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

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

        if (!guests) {
            return guests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.guest_documents_guest = await guests.getGuest_documents_guest({
            transaction
        });
        
        
        
        
        
        
        
        output.reservations_guest = await guests.getReservations_guest({
            transaction
        });
        
        
        output.reservation_guests_guest = await guests.getReservation_guests_guest({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.notifications_guest = await guests.getNotifications_guest({
            transaction
        });
        
        
        
        
        
        
        
        output.hotel = await guests.getHotel({
            transaction
        });
        
        
        output.organizations = await guests.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.first_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'first_name',
                        filter.first_name,
                    ),
                };
            }
            
            if (filter.last_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'last_name',
                        filter.last_name,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.nationality) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'nationality',
                        filter.nationality,
                    ),
                };
            }
            
            if (filter.address_line1) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'address_line1',
                        filter.address_line1,
                    ),
                };
            }
            
            if (filter.address_line2) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'address_line2',
                        filter.address_line2,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.state_region) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'state_region',
                        filter.state_region,
                    ),
                };
            }
            
            if (filter.postal_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'postal_code',
                        filter.postal_code,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.preferences) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'preferences',
                        filter.preferences,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

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

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

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

    
};

