
const db = require('../models');
const FileDBApi = require('./file');
const Utils = require('../utils');
const { createBadRequestError, getCurrentOrganizationId, normalizeInventoryImportRow, prefixImportError, resolveOrganizationReference, resolveTenantIdForOrganization, resolveTenantReference } = require('./inventoryContext');

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 globalAccess = currentUser.app_role?.globalAccess;

        let organizationId = data.organizations || null;
        if (!organizationId && !globalAccess) {
            organizationId = getCurrentOrganizationId(currentUser);
        }

        let tenantId = data.tenant || null;
        if (!tenantId && organizationId) {
            tenantId = await resolveTenantIdForOrganization(organizationId, transaction);
        }

        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( tenantId || null, {
            transaction,
        });
        
        await properties.setOrganizations( organizationId || 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;
        const seenIds = new Set();
        const seenImportHashes = new Set();
        const createdRecords = [];

        for (let index = 0; index < data.length; index += 1) {
            const item = normalizeInventoryImportRow(data[index]);
            const rowNumber = index + 2;

            try {
                const globalAccess = Boolean(currentUser.app_role?.globalAccess);
                let tenantId = null;
                let organizationId = null;

                if (globalAccess) {
                    tenantId = await resolveTenantReference(item.tenant, transaction);
                    organizationId = await resolveOrganizationReference(item.organizations, {
                        tenantId,
                        transaction,
                    });

                    if (!organizationId) {
                        throw createBadRequestError('Organization is required for property import.');
                    }
                } else {
                    organizationId = getCurrentOrganizationId(currentUser);
                }

                if (!tenantId && organizationId) {
                    tenantId = await resolveTenantIdForOrganization(organizationId, transaction);
                }

                item.tenant = tenantId || null;
                item.organizations = organizationId || null;

                const itemId = item.id || null;
                const importHash = item.importHash || null;
                if (options?.ignoreDuplicates) {
                    if ((itemId && seenIds.has(itemId)) || (importHash && seenImportHashes.has(importHash))) {
                        continue;
                    }

                    const duplicateFilters = [];
                    if (itemId) {
                        duplicateFilters.push({ id: itemId });
                    }
                    if (importHash) {
                        duplicateFilters.push({ importHash });
                    }

                    if (duplicateFilters.length) {
                        const existingRecord = await db.properties.findOne({
                            where: {
                                [Op.or]: duplicateFilters,
                            },
                            transaction,
                            paranoid: false,
                        });

                        if (existingRecord) {
                            continue;
                        }
                    }
                }

                if (itemId) {
                    seenIds.add(itemId);
                }
                if (importHash) {
                    seenImportHashes.add(importHash);
                }

                const createdRecord = await this.create(item, {
                    ...options,
                    currentUser,
                    transaction,
                });

                createdRecords.push(createdRecord);
            } catch (error) {
                throw prefixImportError(error, rowNumber);
            }
        }

        return createdRecords;
    }

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

        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;

    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, tenantId, selectedOrganizationId) {
        const filters = [];

        if (!globalAccess && organizationId) {
            filters.push({ organizationsId: organizationId });
        }

        if (tenantId) {
            filters.push({ tenantId: Utils.uuid(tenantId) });
        }

        if (selectedOrganizationId) {
            filters.push({ organizationsId: Utils.uuid(selectedOrganizationId) });
        }

        if (query) {
            filters.push({
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'properties',
                        'name',
                        query,
                    ),
                ],
            });
        }

        const where = filters.length > 1
            ? { [Op.and]: filters }
            : (filters[0] || {});

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

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

    
};

