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

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

        const properties = await db.properties.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        code: data.code
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        city: data.city
        ||
        null
            ,
            
        country: data.country
        ||
        null
            ,
            
        timezone: data.timezone
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await properties.setTenant( data.tenant || null, {
            transaction,
        });
        
        await properties.setOrganizations( data.organizations || null, {
            transaction,
        });
        

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

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.properties.getTableName(),
                belongsToColumn: 'images',
                belongsToId: properties.id,
            },
            data.images,
            options,
        );
        

        return properties;
    }
    

    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 propertiesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                code: item.code
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                city: item.city
            ||
            null
            ,
            
                country: item.country
            ||
            null
            ,
            
                timezone: item.timezone
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < properties.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.properties.getTableName(),
                    belongsToColumn: 'images',
                    belongsToId: properties[i].id,
                },
                data[i].images,
                options,
            );
        }
        

        return properties;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.city !== undefined) updatePayload.city = data.city;
        
        
        if (data.country !== undefined) updatePayload.country = data.country;
        
        
        if (data.timezone !== undefined) updatePayload.timezone = data.timezone;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

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

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.properties.getTableName(),
                belongsToColumn: 'images',
                belongsToId: properties.id,
            },
            data.images,
            options,
        );
        

        return properties;
    }

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

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

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


        return properties;
    }

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

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

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

        await properties.destroy({
            transaction
        });

        return properties;
    }

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

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

        if (!properties) {
            return properties;
        }

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

        
        
        
        
        
        
        
        
        
        output.amenities_property = await properties.getAmenities_property({
            transaction
        });
        
        
        output.unit_types_property = await properties.getUnit_types_property({
            transaction
        });
        
        
        output.units_property = await properties.getUnits_property({
            transaction
        });
        
        
        
        output.negotiated_rates_property = await properties.getNegotiated_rates_property({
            transaction
        });
        
        
        output.booking_requests_preferred_property = await properties.getBooking_requests_preferred_property({
            transaction
        });
        
        
        
        
        output.reservations_property = await properties.getReservations_property({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await properties.getTenant({
            transaction
        });
        
        
        output.images = await properties.getImages({
            transaction
        });
        
        
        output.unit_types = await properties.getUnit_types({
            transaction
        });
        
        
        output.units = await properties.getUnits({
            transaction
        });
        
        
        output.amenities = await properties.getAmenities({
            transaction
        });
        
        
        output.organizations = await properties.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.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: 'organizations',
        
      },


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

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

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


      {
        model: db.file,
        as: 'images',
      },

    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'code',
                        filter.code,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.city) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'city',
                        filter.city,
                    ),
                };
            }
            
            if (filter.country) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'country',
                        filter.country,
                    ),
                };
            }
            
            if (filter.timezone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'timezone',
                        filter.timezone,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'properties',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

            

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

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


      

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

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


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

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

      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.amenities) {
        const searchTerms = filter.amenities.split('|');

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

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

    
};

