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

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

        const unit_types = await db.unit_types.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        code: data.code
        ||
        null
            ,
            
        max_occupancy: data.max_occupancy
        ||
        null
            ,
            
        bedrooms: data.bedrooms
        ||
        null
            ,
            
        bathrooms: data.bathrooms
        ||
        null
            ,
            
        size_sqm: data.size_sqm
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        base_nightly_rate: data.base_nightly_rate
        ||
        null
            ,
            
        base_monthly_rate: data.base_monthly_rate
        ||
        null
            ,
            
        minimum_stay_nights: data.minimum_stay_nights
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await unit_types.setProperty( data.property || null, {
            transaction,
        });
        
        await unit_types.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        
        await unit_types.setUnits(data.units || [], {
            transaction,
        });
        

        

        return unit_types;
    }
    

    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 unit_typesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                code: item.code
            ||
            null
            ,
            
                max_occupancy: item.max_occupancy
            ||
            null
            ,
            
                bedrooms: item.bedrooms
            ||
            null
            ,
            
                bathrooms: item.bathrooms
            ||
            null
            ,
            
                size_sqm: item.size_sqm
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                base_nightly_rate: item.base_nightly_rate
            ||
            null
            ,
            
                base_monthly_rate: item.base_monthly_rate
            ||
            null
            ,
            
                minimum_stay_nights: item.minimum_stay_nights
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return unit_types;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.max_occupancy !== undefined) updatePayload.max_occupancy = data.max_occupancy;
        
        
        if (data.bedrooms !== undefined) updatePayload.bedrooms = data.bedrooms;
        
        
        if (data.bathrooms !== undefined) updatePayload.bathrooms = data.bathrooms;
        
        
        if (data.size_sqm !== undefined) updatePayload.size_sqm = data.size_sqm;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.base_nightly_rate !== undefined) updatePayload.base_nightly_rate = data.base_nightly_rate;
        
        
        if (data.base_monthly_rate !== undefined) updatePayload.base_monthly_rate = data.base_monthly_rate;
        
        
        if (data.minimum_stay_nights !== undefined) updatePayload.minimum_stay_nights = data.minimum_stay_nights;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        
        if (data.units !== undefined) {
            await unit_types.setUnits(data.units, { transaction });
        }
        

        

        return unit_types;
    }

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

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

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


        return unit_types;
    }

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

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

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

        await unit_types.destroy({
            transaction
        });

        return unit_types;
    }

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

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

        if (!unit_types) {
            return unit_types;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.units_unit_type = await unit_types.getUnits_unit_type({
            transaction
        });
        
        
        
        output.negotiated_rates_unit_type = await unit_types.getNegotiated_rates_unit_type({
            transaction
        });
        
        
        output.booking_requests_preferred_unit_type = await unit_types.getBooking_requests_preferred_unit_type({
            transaction
        });
        
        
        
        
        output.reservations_unit_type = await unit_types.getReservations_unit_type({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.property = await unit_types.getProperty({
            transaction
        });
        
        
        output.units = await unit_types.getUnits({
            transaction
        });
        
        
        output.organizations = await unit_types.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.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.organizations,
        as: 'organizations',
        
      },


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


    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'unit_types',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'unit_types',
                        'code',
                        filter.code,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'unit_types',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      

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

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


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

        include = [
          {
            model: db.units,
            as: 'units_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  unit_number: {
                    [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.unit_types.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(
                        'unit_types',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

    
};

