
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,
        
        email: data.email
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        first_name: data.first_name
        ||
        null
            ,
            
        last_name: data.last_name
        ||
        null
            ,
            
        date_of_birth: data.date_of_birth
        ||
        null
            ,
            
        gender: data.gender
        ||
        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
            ,
            
        identity_document_type: data.identity_document_type
        ||
        null
            ,
            
        identity_document_number: data.identity_document_number
        ||
        null
            ,
            
        identity_document_expires_at: data.identity_document_expires_at
        ||
        null
            ,
            
        pii_verified: data.pii_verified
        ||
        false
        
            ,
            
        pii_verified_at: data.pii_verified_at
        ||
        null
            ,
            
        data_retention_status: data.data_retention_status
        ||
        null
            ,
            
        anonymize_after_at: data.anonymize_after_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await guests.setLinked_user( data.linked_user || null, {
            transaction,
        });
        
        await guests.setGdpr_consent( data.gdpr_consent || 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,
                
                email: item.email
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                first_name: item.first_name
            ||
            null
            ,
            
                last_name: item.last_name
            ||
            null
            ,
            
                date_of_birth: item.date_of_birth
            ||
            null
            ,
            
                gender: item.gender
            ||
            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
            ,
            
                identity_document_type: item.identity_document_type
            ||
            null
            ,
            
                identity_document_number: item.identity_document_number
            ||
            null
            ,
            
                identity_document_expires_at: item.identity_document_expires_at
            ||
            null
            ,
            
                pii_verified: item.pii_verified
            ||
            false
        
            ,
            
                pii_verified_at: item.pii_verified_at
            ||
            null
            ,
            
                data_retention_status: item.data_retention_status
            ||
            null
            ,
            
                anonymize_after_at: item.anonymize_after_at
            ||
            null
            ,
            
            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 guests = await db.guests.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.first_name !== undefined) updatePayload.first_name = data.first_name;
        
        
        if (data.last_name !== undefined) updatePayload.last_name = data.last_name;
        
        
        if (data.date_of_birth !== undefined) updatePayload.date_of_birth = data.date_of_birth;
        
        
        if (data.gender !== undefined) updatePayload.gender = data.gender;
        
        
        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.identity_document_type !== undefined) updatePayload.identity_document_type = data.identity_document_type;
        
        
        if (data.identity_document_number !== undefined) updatePayload.identity_document_number = data.identity_document_number;
        
        
        if (data.identity_document_expires_at !== undefined) updatePayload.identity_document_expires_at = data.identity_document_expires_at;
        
        
        if (data.pii_verified !== undefined) updatePayload.pii_verified = data.pii_verified;
        
        
        if (data.pii_verified_at !== undefined) updatePayload.pii_verified_at = data.pii_verified_at;
        
        
        if (data.data_retention_status !== undefined) updatePayload.data_retention_status = data.data_retention_status;
        
        
        if (data.anonymize_after_at !== undefined) updatePayload.anonymize_after_at = data.anonymize_after_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.linked_user !== undefined) {
            await guests.setLinked_user(
              
              data.linked_user,
              
              { transaction }
            );
        }
        
        if (data.gdpr_consent !== undefined) {
            await guests.setGdpr_consent(
              
              data.gdpr_consent,
              
              { 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.bookings_primary_guest = await guests.getBookings_primary_guest({
            transaction
        });
        
        
        output.booking_guests_guest = await guests.getBooking_guests_guest({
            transaction
        });
        
        
        
        
        
        
        
        
        output.service_requests_reported_by = await guests.getService_requests_reported_by({
            transaction
        });
        
        
        
        
        
        output.linked_user = await guests.getLinked_user({
            transaction
        });
        
        
        output.gdpr_consent = await guests.getGdpr_consent({
            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.users,
        as: 'linked_user',
        
        where: filter.linked_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.linked_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.linked_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            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.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.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.identity_document_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'guests',
                        'identity_document_number',
                        filter.identity_document_number,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.gender) {
                where = {
                    ...where,
                gender: filter.gender,
            };
            }
            
            if (filter.identity_document_type) {
                where = {
                    ...where,
                identity_document_type: filter.identity_document_type,
            };
            }
            
            if (filter.pii_verified) {
                where = {
                    ...where,
                pii_verified: filter.pii_verified,
            };
            }
            
            if (filter.data_retention_status) {
                where = {
                    ...where,
                data_retention_status: filter.data_retention_status,
            };
            }
            


      

      



            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.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, ) {
        let where = {};
        
        

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

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

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

    
};

