
const db = require('../models');
const Utils = require('../utils');
const config = require('../../config');


const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

function isCustomerUser(currentUser) {
    return currentUser?.app_role?.name === config.roles.customer;
}

async function customerCanAccessReservation(reservation, currentUser, transaction) {
    if (!reservation || !isCustomerUser(currentUser)) {
        return true;
    }

    if (!reservation.booking_requestId) {
        return false;
    }

    const bookingRequest = await db.booking_requests.findOne({
        where: {
            id: reservation.booking_requestId,
            requested_byId: currentUser.id,
        },
        transaction,
    });

    return Boolean(bookingRequest);
}

module.exports = class ReservationsDBApi {
    

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

        const reservations = await db.reservations.create(
            {
                id: data.id || undefined,
        
        reservation_code: data.reservation_code
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        check_in_at: data.check_in_at
        ||
        null
            ,
            
        check_out_at: data.check_out_at
        ||
        null
            ,
            
        actual_check_in_at: data.actual_check_in_at
        ||
        null
            ,
            
        actual_check_out_at: data.actual_check_out_at
        ||
        null
            ,
            
        early_check_in: data.early_check_in
        ||
        false
        
            ,
            
        late_check_out: data.late_check_out
        ||
        false
        
            ,
            
        guest_count: data.guest_count
        ||
        null
            ,
            
        nightly_rate: data.nightly_rate
        ||
        null
            ,
            
        monthly_rate: data.monthly_rate
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        internal_notes: data.internal_notes
        ||
        null
            ,
            
        external_notes: data.external_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await reservations.setTenant( data.tenant || null, {
            transaction,
        });
        
        await reservations.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await reservations.setBooking_request( data.booking_request || null, {
            transaction,
        });
        
        await reservations.setProperty( data.property || null, {
            transaction,
        });
        
        await reservations.setUnit( data.unit || null, {
            transaction,
        });
        
        await reservations.setUnit_type( data.unit_type || null, {
            transaction,
        });
        

        
        await reservations.setGuests(data.guests || [], {
            transaction,
        });
        
        await reservations.setService_requests(data.service_requests || [], {
            transaction,
        });
        
        await reservations.setInvoices(data.invoices || [], {
            transaction,
        });
        
        await reservations.setDocuments(data.documents || [], {
            transaction,
        });
        
        await reservations.setComments(data.comments || [], {
            transaction,
        });
        

        

        return reservations;
    }
    

    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 reservationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                reservation_code: item.reservation_code
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                check_in_at: item.check_in_at
            ||
            null
            ,
            
                check_out_at: item.check_out_at
            ||
            null
            ,
            
                actual_check_in_at: item.actual_check_in_at
            ||
            null
            ,
            
                actual_check_out_at: item.actual_check_out_at
            ||
            null
            ,
            
                early_check_in: item.early_check_in
            ||
            false
        
            ,
            
                late_check_out: item.late_check_out
            ||
            false
        
            ,
            
                guest_count: item.guest_count
            ||
            null
            ,
            
                nightly_rate: item.nightly_rate
            ||
            null
            ,
            
                monthly_rate: item.monthly_rate
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                internal_notes: item.internal_notes
            ||
            null
            ,
            
                external_notes: item.external_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return reservations;
    }

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


        

        const updatePayload = {};
        
        if (data.reservation_code !== undefined) updatePayload.reservation_code = data.reservation_code;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.check_in_at !== undefined) updatePayload.check_in_at = data.check_in_at;
        
        
        if (data.check_out_at !== undefined) updatePayload.check_out_at = data.check_out_at;
        
        
        if (data.actual_check_in_at !== undefined) updatePayload.actual_check_in_at = data.actual_check_in_at;
        
        
        if (data.actual_check_out_at !== undefined) updatePayload.actual_check_out_at = data.actual_check_out_at;
        
        
        if (data.early_check_in !== undefined) updatePayload.early_check_in = data.early_check_in;
        
        
        if (data.late_check_out !== undefined) updatePayload.late_check_out = data.late_check_out;
        
        
        if (data.guest_count !== undefined) updatePayload.guest_count = data.guest_count;
        
        
        if (data.nightly_rate !== undefined) updatePayload.nightly_rate = data.nightly_rate;
        
        
        if (data.monthly_rate !== undefined) updatePayload.monthly_rate = data.monthly_rate;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.internal_notes !== undefined) updatePayload.internal_notes = data.internal_notes;
        
        
        if (data.external_notes !== undefined) updatePayload.external_notes = data.external_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await reservations.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.organization !== undefined) {
            await reservations.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.booking_request !== undefined) {
            await reservations.setBooking_request(
              
              data.booking_request,
              
              { transaction }
            );
        }
        
        if (data.property !== undefined) {
            await reservations.setProperty(
              
              data.property,
              
              { transaction }
            );
        }
        
        if (data.unit !== undefined) {
            await reservations.setUnit(
              
              data.unit,
              
              { transaction }
            );
        }
        
        if (data.unit_type !== undefined) {
            await reservations.setUnit_type(
              
              data.unit_type,
              
              { transaction }
            );
        }
        

        
        
        if (data.guests !== undefined) {
            await reservations.setGuests(data.guests, { transaction });
        }
        
        if (data.service_requests !== undefined) {
            await reservations.setService_requests(data.service_requests, { transaction });
        }
        
        if (data.invoices !== undefined) {
            await reservations.setInvoices(data.invoices, { transaction });
        }
        
        if (data.documents !== undefined) {
            await reservations.setDocuments(data.documents, { transaction });
        }
        
        if (data.comments !== undefined) {
            await reservations.setComments(data.comments, { transaction });
        }
        

        

        return reservations;
    }

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

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

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


        return reservations;
    }

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

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

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

        await reservations.destroy({
            transaction
        });

        return reservations;
    }

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

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

        if (!reservations) {
            return reservations;
        }

        if (!(await customerCanAccessReservation(reservations, currentUser, transaction))) {
            return null;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.unit_availability_blocks_reservation = await reservations.getUnit_availability_blocks_reservation({
            transaction
        });
        
        
        
        
        
        
        
        output.reservation_guests_reservation = await reservations.getReservation_guests_reservation({
            transaction
        });
        
        
        output.service_requests_reservation = await reservations.getService_requests_reservation({
            transaction
        });
        
        
        output.invoices_reservation = await reservations.getInvoices_reservation({
            transaction
        });
        
        
        
        
        output.documents_reservation = await reservations.getDocuments_reservation({
            transaction
        });
        
        
        
        
        output.activity_comments_reservation = await reservations.getActivity_comments_reservation({
            transaction
        });
        
        
        output.checklists_reservation = await reservations.getChecklists_reservation({
            transaction
        });
        
        
        
        
        
        output.tenant = await reservations.getTenant({
            transaction
        });
        
        
        output.organization = await reservations.getOrganization({
            transaction
        });
        
        
        output.booking_request = await reservations.getBooking_request({
            transaction
        });
        
        
        output.property = await reservations.getProperty({
            transaction
        });
        
        
        output.unit = await reservations.getUnit({
            transaction
        });
        
        
        output.unit_type = await reservations.getUnit_type({
            transaction
        });
        
        
        output.guests = await reservations.getGuests({
            transaction
        });
        
        
        output.service_requests = await reservations.getService_requests({
            transaction
        });
        
        
        output.invoices = await reservations.getInvoices({
            transaction
        });
        
        
        output.documents = await reservations.getDocuments({
            transaction
        });
        
        
        output.comments = await reservations.getComments({
            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;
        const isCustomer = isCustomerUser(user);
        

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

        offset = currentPage * limit;


    let include = [

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

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

      {
        model: db.booking_requests,
        as: 'booking_request',
        required: isCustomer || Boolean(filter.booking_request),
        where: {
          ...(isCustomer ? { requested_byId: user.id } : {}),
          ...(filter.booking_request ? {
            [Op.or]: [
              { id: { [Op.in]: filter.booking_request.split('|').map(term => Utils.uuid(term)) } },
              {
                request_code: {
                  [Op.or]: filter.booking_request.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
                }
              },
            ]
          } : {}),
        },
        
      },

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

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

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


      {
        model: db.reservation_guests,
        as: 'guests',
        required: false,
      },

      {
        model: db.service_requests,
        as: 'service_requests',
        required: false,
      },

      {
        model: db.invoices,
        as: 'invoices',
        required: false,
      },

      {
        model: db.documents,
        as: 'documents',
        required: false,
      },

      {
        model: db.activity_comments,
        as: 'comments',
        required: false,
      },


    ];

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

            
            if (filter.reservation_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reservations',
                        'reservation_code',
                        filter.reservation_code,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reservations',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.internal_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reservations',
                        'internal_notes',
                        filter.internal_notes,
                    ),
                };
            }
            
            if (filter.external_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reservations',
                        'external_notes',
                        filter.external_notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            check_in_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    check_out_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.early_check_in) {
                where = {
                    ...where,
                early_check_in: filter.early_check_in,
            };
            }
            
            if (filter.late_check_out) {
                where = {
                    ...where,
                late_check_out: filter.late_check_out,
            };
            }
            


      

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

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

      

      

      

      


      if (filter.guests) {
        const searchTerms = filter.guests.split('|');

        include = [
          {
            model: db.reservation_guests,
            as: 'guests_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  full_name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.service_requests) {
        const searchTerms = filter.service_requests.split('|');

        include = [
          {
            model: db.service_requests,
            as: 'service_requests_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  summary: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.invoices) {
        const searchTerms = filter.invoices.split('|');

        include = [
          {
            model: db.invoices,
            as: 'invoices_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  invoice_number: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.documents) {
        const searchTerms = filter.documents.split('|');

        include = [
          {
            model: db.documents,
            as: 'documents_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  file_name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.comments) {
        const searchTerms = filter.comments.split('|');

        include = [
          {
            model: db.activity_comments,
            as: 'comments_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  body: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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.reservations.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, currentUser) {
        let where = {};
        const include = [];
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

        if (isCustomerUser(currentUser)) {
            include.push({
                model: db.booking_requests,
                as: 'booking_request',
                required: true,
                where: { requested_byId: currentUser.id },
            });
        }

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

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

    
};

