"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PostpropertymasterController = void 0;
const tslib_1 = require("tslib");
/* eslint-disable @typescript-eslint/no-misused-promises */
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/naming-convention */
const core_1 = require("@loopback/core");
const repository_1 = require("@loopback/repository");
const rest_1 = require("@loopback/rest");
const axios_1 = tslib_1.__importDefault(require("axios"));
const constants_1 = require("../config/constants");
const models_1 = require("../models");
const repositories_1 = require("../repositories");
const fs_1 = tslib_1.__importDefault(require("fs"));
const multer_1 = tslib_1.__importDefault(require("multer"));
const path_1 = tslib_1.__importDefault(require("path"));
const BASE_URL = constants_1.URL;
const FALLBACK_URL = `${BASE_URL}/default.jpg`;
// --- Helper to resolve any type of photo value ---
function resolvePhoto(photo) {
    if (!photo)
        return FALLBACK_URL;
    const filename = path_1.default.basename(photo);
    // Return correct URL that points to the served static folder
    return `${BASE_URL}/uploads/property-images/${filename}`;
}
function resolveVideo(video) {
    if (!video)
        return FALLBACK_URL;
    const filename = path_1.default.basename(video);
    return `${BASE_URL}/uploads/property-images/${filename}`;
}
// --- Normalize property (main + multiple photos) ---
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function normalizeProperty(item) {
    let photosArray = [];
    try {
        photosArray = item.photos ? JSON.parse(item.photos) : [];
    }
    catch (err) {
        console.error('Error parsing photos JSON:', err);
        photosArray = [];
    }
    return {
        ...item,
        photo: resolvePhoto(item.photo),
        photos: photosArray.map((f) => resolvePhoto(f)),
        video: resolveVideo(item.video),
    };
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function pickIdAndName(obj, idField, nameField) {
    if (!obj)
        return null;
    return {
        [idField]: obj[idField],
        [nameField]: obj[nameField],
    };
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
// In postpropertymaster.controller.ts
function transformProperty(item) {
    if (!item)
        return item;
    const normalized = normalizeProperty(item);
    // Transform amenities array properly
    let amenitiesArray = [];
    if (item.amenities && Array.isArray(item.amenities)) {
        amenitiesArray = item.amenities.map((amenity) => ({
            amenitiesId: amenity.amenitiesId,
            amenitiesName: amenity.amenitiesName,
        }));
    }
    return {
        // ...normalized,
        annualduespay: normalized.annualduespay,
        apartmentNameAreaName: normalized.apartmentNameAreaName,
        bookingamount: normalized.bookingamount,
        builduparea: normalized.builduparea,
        carpetarea: normalized.carpetarea,
        coverparking: normalized.coverparking,
        description: normalized.description,
        expectedrental: normalized.expectedrental,
        fkavailablestatusId: normalized.fkavailablestatusId,
        fksellerId: normalized.fksellerId,
        publish_Fag: normalized.publish_Fag,
        fkpublish_TypeId: normalized.fkpublish_TypeId,
        publish_StartDate: normalized.publish_StartDate,
        publish_EndDate: normalized.publish_EndDate,
        fkcityId: normalized.fkcityId,
        fkfloorId: normalized.fkfloorId,
        fkfurnishingtypeId: normalized.fkfurnishingtypeId,
        fktransactionId: normalized.fktransactionId,
        fkpossessionId: normalized.fkpossessionId,
        fkfacingId: normalized.fkfacingId,
        // Remove fkamenitiesId from the response
        // fkamenitiesId: normalized.fkamenitiesId,
        fklocalityId: normalized.fklocalityId,
        fkmainpropertytypeId: normalized.fkmainpropertytypeId,
        fkmaintnecemonthId: normalized.fkmaintnecemonthId,
        fkotherrooms: normalized.fkotherrooms,
        fkownershipId: normalized.fkownershipId,
        fkuserId: normalized.fkuserId,
        fkpostpropertytypeId: normalized.fkpostpropertytypeId,
        fkpropertytypeId: normalized.fkpropertytypeId,
        housenumber: normalized.housenumber,
        isActive: normalized.isActive,
        maintenance: normalized.maintenance,
        membershipcharge: normalized.membershipcharge,
        noofbalkanies: normalized.noofbalkanies,
        noofbathrooms: normalized.noofbathrooms,
        noofbedrooms: normalized.noofbedrooms,
        openparking: normalized.openparking,
        photo: normalized.photo,
        photos: normalized.photos,
        postpropertyId: normalized.postpropertyId,
        price: normalized.price,
        RERA_NO: normalized.RERA_NO,
        RERA_is_active: normalized.RERA_is_active,
        pricepersqft: normalized.pricepersqft,
        sublocality: normalized.sublocality,
        Property_Title: normalized.Property_Title,
        Property_Description: normalized.Property_Description,
        supperbuilduparea: normalized.supperbuilduparea,
        totalfloor: normalized.totalfloor,
        video: normalized.video,
        availableStatus: pickIdAndName(item.availableStatus, 'availableStatusId', 'availableStatusName'),
        seller: pickIdAndName(item.seller, 'sellerId', 'sellerName'),
        publishType: pickIdAndName(item.publishType, 'publishTypeId', 'publishTypeName'),
        floor: pickIdAndName(item.floor, 'floorId', 'floorName'),
        furnishingType: pickIdAndName(item.furnishingType, 'furnishingTypeId', 'furnishingTypeName'),
        possessionType: pickIdAndName(item.possessionType, 'possessionId', 'possessionName'),
        transactionType: pickIdAndName(item.transactionType, 'transactionId', 'transactionName'),
        mainPropertyType: pickIdAndName(item.mainPropertyType, 'mainpropertytypeId', 'mainprpoertyName'),
        maintenanceMonth: pickIdAndName(item.maintenanceMonth, 'maintenanceMonthId', 'maintenanceMonthName'),
        otherRoom: pickIdAndName(item.otherRoom, 'otherRoomId', 'otherRoomName'),
        ownership: pickIdAndName(item.ownership, 'ownershipId', 'ownershipName'),
        userType: pickIdAndName(item.userType, 'userTypeId', 'userTypeName'),
        postType: pickIdAndName(item.postType, 'postTypeId', 'posttypeName'),
        propertyType: pickIdAndName(item.propertyType, 'propertyTypeId', 'propertytypeName'),
        facing: pickIdAndName(item.facing, 'facingId', 'facingName'),
        // Use the properly transformed amenities array
        amenities: amenitiesArray,
    };
}
// --- Relations list ---
const allRelations = [
    // {relation: 'city'},
    { relation: 'availableStatus' },
    { relation: 'seller' },
    { relation: 'publishType' },
    { relation: 'floor' },
    { relation: 'furnishingType' },
    { relation: 'transactionType' },
    { relation: 'possessionType' },
    { relation: 'mainPropertyType' },
    { relation: 'maintenanceMonth' },
    { relation: 'otherRoom' },
    { relation: 'ownership' },
    { relation: 'userType' },
    { relation: 'postType' },
    { relation: 'propertyType' },
    { relation: 'amenities' },
    { relation: 'facing' },
];
// --- Numeric Fields for robust parsing ---
const numericFields = [
    'price',
    'pricepersqft',
    'builduparea',
    'carpetarea',
    'supperbuilduparea',
    'annualduespay',
    'bookingamount',
    'coverparking',
    'openparking',
    'expectedrental',
    'maintenance',
    'membershipcharge',
    'totalfloor',
    'noofbedrooms',
    'noofbathrooms',
    'noofbalkanies',
    'fkavailablestatusId',
    'fksellerId',
    'fkpublish_TypeId',
    'fkfloorId',
    'fkfurnishingtypeId',
    'fkpossessionId',
    'fktransactionId',
    'fkmainpropertytypeId',
    'fkmaintnecemonthId',
    'fkotherrooms',
    'fkownershipId',
    'fkuserId',
    'fkpostpropertytypeId',
    'fkpropertytypeId',
    'publish_Fag',
    'fkfacingId',
    'isReraRegistered',
];
let PostpropertymasterController = class PostpropertymasterController {
    constructor(postPropertyMasterRepository, recommendedLaunchRepository, bestpropertyLaunch, propertyAmenitiesRepository, newLaunchRepository) {
        this.postPropertyMasterRepository = postPropertyMasterRepository;
        this.recommendedLaunchRepository = recommendedLaunchRepository;
        this.bestpropertyLaunch = bestpropertyLaunch;
        this.propertyAmenitiesRepository = propertyAmenitiesRepository;
        this.newLaunchRepository = newLaunchRepository;
    }
    async saveImageFromPathOrUrl(imagePath) {
        const uploadDir = path_1.default.join(__dirname, '../../uploads/property-images');
        if (!fs_1.default.existsSync(uploadDir))
            fs_1.default.mkdirSync(uploadDir, { recursive: true });
        const fileName = Date.now() + '-' + path_1.default.basename(imagePath);
        if (imagePath.startsWith('http')) {
            // eslint-disable-next-line @typescript-eslint/no-shadow
            const response = await axios_1.default.get(imagePath, { responseType: 'arraybuffer' });
            fs_1.default.writeFileSync(path_1.default.join(uploadDir, fileName), response.data);
        }
        else if (fs_1.default.existsSync(imagePath)) {
            fs_1.default.copyFileSync(imagePath, path_1.default.join(uploadDir, fileName));
        }
        else {
            throw new Error(`Image not found: ${imagePath}`);
        }
        return fileName;
    }
    getMulterUpload() {
        const storage = multer_1.default.diskStorage({
            destination: (req, file, cb) => {
                const dir = path_1.default.join(__dirname, '../../uploads/property-images');
                if (!fs_1.default.existsSync(dir))
                    fs_1.default.mkdirSync(dir, { recursive: true });
                cb(null, dir);
            },
            filename: (req, file, cb) => {
                cb(null, Date.now() + '-' + file.originalname);
            },
        });
        return (0, multer_1.default)({ storage });
    }
    // Create property with multiple photo upload
    // In postpropertymaster.controller.ts
    async createWithPhotos(request) {
        const upload = this.getMulterUpload().fields([
            { name: 'photo', maxCount: 15 },
            { name: 'video', maxCount: 1 },
        ]);
        return new Promise((resolve, reject) => {
            upload(request, {}, async (err) => {
                var _a;
                if (err)
                    return reject(err);
                try {
                    const files = request.files;
                    const imageFiles = (files === null || files === void 0 ? void 0 : files.photo) || [];
                    const videoFile = ((_a = files === null || files === void 0 ? void 0 : files.video) === null || _a === void 0 ? void 0 : _a[0]) || null;
                    const photos = imageFiles.map((f) => f.filename);
                    const amenitiesData = request.body.amenities;
                    const bodyData = {};
                    for (const key in request.body) {
                        let value = request.body[key];
                        if (value === undefined || value === 'undefined')
                            continue;
                        if (key === 'amenities')
                            continue;
                        if (value === 'null' || value === '' || value === null) {
                            value = null;
                        }
                        if (numericFields.includes(key)) {
                            if (value === null) {
                                bodyData[key] = null;
                            }
                            else {
                                const parsed = Number(value);
                                if (!isFinite(parsed)) {
                                    bodyData[key] = null;
                                }
                                else {
                                    bodyData[key] = parsed;
                                }
                            }
                        }
                        else {
                            bodyData[key] = value;
                        }
                    }
                    if (bodyData.isReraRegistered !== undefined) {
                        bodyData.RERA_is_active = bodyData.isReraRegistered;
                        delete bodyData.isReraRegistered;
                    }
                    // Remove fkamenitiesId from bodyData if it exists
                    if (bodyData.fkamenitiesId !== undefined) {
                        delete bodyData.fkamenitiesId;
                    }
                    // FINAL SAFETY SWEEP: Ensure no numeric NaN remains in the final object
                    Object.keys(bodyData).forEach(key => {
                        const value = bodyData[key];
                        if (typeof value === 'number' && !isFinite(value)) {
                            bodyData[key] = null;
                        }
                    });
                    const saved = await this.postPropertyMasterRepository.create({
                        ...bodyData,
                        createdDate: new Date().toISOString(),
                        photos: JSON.stringify(photos),
                        photo: photos[0] || null,
                        video: (videoFile === null || videoFile === void 0 ? void 0 : videoFile.filename) || null,
                    });
                    if (amenitiesData) {
                        try {
                            let amenitiesIds = [];
                            if (typeof amenitiesData === 'string') {
                                amenitiesIds = JSON.parse(amenitiesData);
                            }
                            else if (Array.isArray(amenitiesData)) {
                                amenitiesIds = amenitiesData
                                    .map(id => Number(id))
                                    .filter(id => !isNaN(id) && id > 0);
                            }
                            // console.log('📋 Amenities to save:', amenitiesIds);
                            // console.log('🏠 Property ID:', saved.postpropertyId);
                            if (amenitiesIds.length > 0 && saved.postpropertyId) {
                                for (const amenityId of amenitiesIds) {
                                    const amenityRecord = {
                                        postpropertyId: saved.postpropertyId,
                                        amenitiesId: amenityId,
                                        createdDate: new Date().toISOString(),
                                        lastChanged: new Date().toISOString(), // ✅ ADD THIS
                                    };
                                    // console.log('💾 Saving amenity record:', amenityRecord);
                                    await this.propertyAmenitiesRepository.create(amenityRecord);
                                    // console.log('✅ Amenity saved successfully');
                                }
                            }
                            else {
                                console.log('⚠️ No amenities to save or property ID missing');
                            }
                        }
                        catch (e) {
                            console.error('❌ Error saving amenities:', e);
                            // Don't throw - just log, so property still saves
                        }
                    }
                    resolve(normalizeProperty(saved));
                }
                catch (e) {
                    reject(e);
                }
            });
        });
    }
    async create(postPropertyMaster) {
        const property = await this.postPropertyMasterRepository.create(postPropertyMaster);
        return normalizeProperty(property);
    }
    async count(where) {
        return this.postPropertyMasterRepository.count(where);
    }
    // In postpropertymaster.controller.ts
    async find(filter) {
        const data = await this.postPropertyMasterRepository.find({
            ...filter,
            include: [
                ...allRelations,
                {
                    relation: 'amenities',
                    scope: {
                        fields: {
                            amenitiesId: true,
                            amenitiesName: true,
                        }
                    }
                }
            ],
            order: ['created_date DESC'],
        });
        return data.map(transformProperty);
    }
    async updateAll(postPropertyMaster, where) {
        return this.postPropertyMasterRepository.updateAll(postPropertyMaster, where);
    }
    // In postpropertymaster.controller.ts
    async findById(id, filter) {
        const item = await this.postPropertyMasterRepository.findById(id, {
            ...filter,
            include: [
                ...allRelations,
                {
                    relation: 'amenities',
                    scope: {
                        fields: {
                            amenitiesId: true,
                            amenitiesName: true,
                        }
                    }
                }
            ],
            order: ['created_date DESC'],
        });
        return normalizeProperty(item);
    }
    async getRecommended() {
        const data = await this.postPropertyMasterRepository.find({
            where: { and: [{ fkpublish_TypeId: 1 }, { publish_Fag: 2 }] },
            order: ['created_date DESC'],
            include: allRelations,
        });
        return data.map(transformProperty);
    }
    async getRecommendedFromRecommendedLaunch() {
        const recommended = await this.recommendedLaunchRepository.find();
        const propertyIds = recommended.map(item => item.fkpostpropertyId);
        if (propertyIds.length === 0)
            return [];
        const properties = await this.postPropertyMasterRepository.find({
            where: { postpropertyId: { inq: propertyIds } },
            include: allRelations,
        });
        const sortedProperties = propertyIds
            .map(id => properties.find(p => p.postpropertyId === id))
            .filter(p => p)
            .slice(0, 4); // ⚡ Get 4 properties
        return sortedProperties.map(transformProperty);
    }
    async getBestValue() {
        const data = await this.postPropertyMasterRepository.find({
            where: { and: [{ fkpublish_TypeId: 2 }, { publish_Fag: 2 }] },
            order: ['created_date DESC'],
            include: allRelations,
        });
        return data.map(transformProperty);
    }
    async getBestpropertyFromBestLaunch() {
        const best = await this.bestpropertyLaunch.find();
        const propertyIds = best.map(item => item.fkpostpropertyId);
        if (propertyIds.length === 0)
            return [];
        const properties = await this.postPropertyMasterRepository.find({
            where: { postpropertyId: { inq: propertyIds } },
            include: allRelations,
        });
        return properties.map(transformProperty);
    }
    async getNewLaunchFromLaunchTable() {
        const newLaunch = await this.newLaunchRepository.find();
        const propertyIds = newLaunch.map(item => item.fkpostpropertyId);
        if (propertyIds.length === 0)
            return [];
        const properties = await this.postPropertyMasterRepository.find({
            where: {
                postpropertyId: { inq: propertyIds },
                publish_Fag: 2,
                isActive: 1,
            },
            include: allRelations,
        });
        // Optional: sequence maintain करायचा असेल तर
        const sortedProperties = propertyIds
            .map(id => properties.find(p => p.postpropertyId === id))
            .filter(p => p)
            .slice(0, 3); // ⚡ limit 4
        return sortedProperties.map(transformProperty);
    }
    async getAllNewLaunch() {
        const data = await this.postPropertyMasterRepository.find({
            where: { and: [{ fkpublish_TypeId: 3 }, { publish_Fag: 2 }] },
            order: ['created_date DESC'],
            include: allRelations,
        });
        return data.map(transformProperty);
    }
    // In postpropertymaster.controller.ts
    async updateWithPhotos(id, request) {
        const upload = this.getMulterUpload().fields([
            { name: 'photo', maxCount: 15 },
            { name: 'video', maxCount: 1 },
        ]);
        return new Promise((resolve, reject) => {
            upload(request, {}, async (err) => {
                var _a;
                if (err)
                    return reject(err);
                try {
                    const files = request.files;
                    const imageFiles = (files === null || files === void 0 ? void 0 : files.photo) || [];
                    const videoFile = ((_a = files === null || files === void 0 ? void 0 : files.video) === null || _a === void 0 ? void 0 : _a[0]) || null;
                    const updateData = {};
                    const amenitiesData = request.body.amenities;
                    // Parse body fields
                    for (const key in request.body) {
                        let value = request.body[key];
                        if (value === undefined || value === 'undefined')
                            continue;
                        if (value === 'null' || value === '') {
                            value = null;
                        }
                        if (key === 'amenities' || key === 'existingPhotos')
                            continue;
                        if (value === 'true' || value === 'false') {
                            value = value === 'true';
                        }
                        if (numericFields.includes(key)) {
                            if (value === null) {
                                updateData[key] = null;
                            }
                            else {
                                const parsed = Number(value);
                                if (!isFinite(parsed)) {
                                    updateData[key] = null;
                                }
                                else {
                                    updateData[key] = parsed;
                                }
                            }
                        }
                        else {
                            updateData[key] = value;
                        }
                    }
                    if (updateData.isReraRegistered !== undefined) {
                        updateData.RERA_is_active = updateData.isReraRegistered;
                        delete updateData.isReraRegistered;
                    }
                    // Remove fkamenitiesId from updateData if it exists
                    if (updateData.fkamenitiesId !== undefined) {
                        delete updateData.fkamenitiesId;
                    }
                    // Handle Photos - Merge existing + new
                    let allPhotos = [];
                    if (request.body.existingPhotos) {
                        try {
                            const existingPhotoUrls = JSON.parse(request.body.existingPhotos);
                            allPhotos = existingPhotoUrls.map((url) => {
                                const urlParts = url.split('/');
                                return urlParts[urlParts.length - 1];
                            });
                        }
                        catch (e) {
                            console.error('Error parsing existing photos:', e);
                        }
                    }
                    if (imageFiles.length > 0) {
                        const newPhotos = imageFiles.map((f) => f.filename);
                        allPhotos = [...allPhotos, ...newPhotos];
                    }
                    if (allPhotos.length > 0) {
                        updateData.photos = JSON.stringify(allPhotos);
                        updateData.photo = allPhotos[0];
                    }
                    if (videoFile) {
                        updateData.video = videoFile.filename;
                    }
                    await this.postPropertyMasterRepository.updateById(id, updateData);
                    // Handle amenities relationship update
                    if (amenitiesData) {
                        try {
                            let amenitiesIds = [];
                            if (typeof amenitiesData === 'string') {
                                amenitiesIds = JSON.parse(amenitiesData);
                            }
                            else if (Array.isArray(amenitiesData)) {
                                amenitiesIds = amenitiesData
                                    .map(aid => Number(aid))
                                    .filter(aid => !isNaN(aid) && aid > 0);
                            }
                            // console.log('📋 Updating amenities with IDs:', amenitiesIds);
                            // Delete old amenities relationships
                            await this.propertyAmenitiesRepository.deleteAll({
                                postpropertyId: id,
                            });
                            // console.log('🗑️ Old amenities deleted');
                            // Create new amenities relationships
                            if (amenitiesIds && amenitiesIds.length > 0) {
                                for (const amenityId of amenitiesIds) {
                                    const amenityRecord = {
                                        postpropertyId: id,
                                        amenitiesId: amenityId,
                                        createdDate: new Date().toISOString(),
                                        lastChanged: new Date().toISOString(), // ✅ ADD THIS
                                    };
                                    // console.log('💾 Creating amenity record:', amenityRecord);
                                    await this.propertyAmenitiesRepository.create(amenityRecord);
                                }
                                // console.log('✅ Amenities updated successfully');
                            }
                        }
                        catch (e) {
                            console.error('❌ Error updating amenities:', e);
                            // Don't throw - just log
                        }
                    }
                    resolve();
                }
                catch (e) {
                    reject(e);
                }
            });
        });
    }
    async replaceById(id, postPropertyMaster) {
        await this.postPropertyMasterRepository.replaceById(id, postPropertyMaster);
    }
    async deleteById(id) {
        await this.postPropertyMasterRepository.deleteById(id);
    }
    // --- New Published/Active Query Methods ---
    async getPublishedActive(fkcityId, fkpostType, fklocalityId, fkpropertytypeId, fkfurnishingtypeId, fktransactionId, fkpossessionId, fkfacingId, fkmainpropertytypeId, fkuserId, RERA_is_active, Property_Title) {
        const baseWhere = [{ isActive: 1 }, { publish_Fag: 2 }];
        if (fkcityId) {
            baseWhere.push({ fkcityId });
        }
        // fkpostType maps to fkpostpropertytypeId in the model
        if (fkpostType !== undefined) {
            baseWhere.push({ fkpostpropertytypeId: fkpostType });
        }
        if (fklocalityId) {
            baseWhere.push({ fklocalityId });
        }
        if (fkpropertytypeId !== undefined) {
            baseWhere.push({ fkpropertytypeId });
        }
        if (fkfurnishingtypeId !== undefined) {
            baseWhere.push({ fkfurnishingtypeId });
        }
        //
        if (fktransactionId !== undefined) {
            baseWhere.push({ fktransactionId });
        }
        if (fkpossessionId !== undefined) {
            baseWhere.push({ fkpossessionId });
        }
        if (fkfacingId !== undefined) {
            baseWhere.push({ fkfacingId });
        }
        // ⚠️ NOTE: fkamenitiesId is generally handled via a relation,
        // but if it's a direct column in PostPropertyMaster, this is okay.
        // if (fkamenitiesId !== undefined) {
        //  baseWhere.push({fkamenitiesId});
        // }
        if (fkmainpropertytypeId !== undefined) {
            baseWhere.push({ fkmainpropertytypeId });
        }
        if (fkuserId !== undefined) {
            baseWhere.push({ fkuserId });
        }
        // fkpostpropertytypeId is already handled by fkpostType
        if (RERA_is_active !== undefined) {
            baseWhere.push({ RERA_is_active });
        }
        if (Property_Title) {
            // 💡 Consideration: Use a LIKE query for partial matching if needed
            // baseWhere.push({ Property_Title: { like: `%${Property_Title}%` } });
            baseWhere.push({ Property_Title });
        }
        const finalFilter = {
            where: { and: baseWhere },
            order: ['created_date DESC'],
            include: allRelations,
        };
        const data = await this.postPropertyMasterRepository.find(finalFilter);
        return data.map(transformProperty);
    }
    async getPublishedActiveById(id, filter) {
        const item = await this.postPropertyMasterRepository.findOne({
            where: {
                and: [
                    { postpropertyId: id },
                    { isActive: 1 },
                    { publish_Fag: 2 }, // Must be published
                ],
            },
            // Use the filter to include relations if specified in the query, but we override 'where'
            ...filter,
            include: allRelations, // Include all related models
        });
        if (!item) {
            // Throw a standard 404 error if the item is not found or not active/ published
            throw new rest_1.HttpErrors.NotFound(`PostPropertyMaster with id ${id} (active and published) not found`);
        }
        // Transform the data to normalize photo URLs and return only selected fields
        return transformProperty(item);
    }
};
exports.PostpropertymasterController = PostpropertymasterController;
tslib_1.__decorate([
    (0, rest_1.post)('/post-property-masters/uploads'),
    (0, rest_1.response)(200, {
        description: 'PostPropertyMaster model instance',
    }),
    tslib_1.__param(0, (0, core_1.inject)(rest_1.RestBindings.Http.REQUEST)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "createWithPhotos", null);
tslib_1.__decorate([
    (0, rest_1.post)('/post-property-masters'),
    (0, rest_1.response)(200, {
        description: 'PostPropertyMaster model instance',
        content: {
            'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.PostPropertyMaster) },
        },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.PostPropertyMaster, {
                    title: 'NewPostPropertyMaster',
                    exclude: ['postpropertyId'],
                }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "create", null);
tslib_1.__decorate([
    (0, rest_1.get)('/post-property-masters/count'),
    (0, rest_1.response)(200, {
        description: 'PostPropertyMaster model count',
        content: { 'application/json': { schema: repository_1.CountSchema } },
    }),
    tslib_1.__param(0, rest_1.param.where(models_1.PostPropertyMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "count", null);
tslib_1.__decorate([
    (0, rest_1.get)('/post-property-masters'),
    (0, rest_1.response)(200, {
        description: 'Array of PostPropertyMaster model instances',
    }),
    tslib_1.__param(0, rest_1.param.filter(models_1.PostPropertyMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "find", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/post-property-masters'),
    (0, rest_1.response)(200, {
        description: 'PostPropertyMaster PATCH success count',
        content: { 'application/json': { schema: repository_1.CountSchema } },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.PostPropertyMaster, { partial: true }),
            },
        },
    })),
    tslib_1.__param(1, rest_1.param.where(models_1.PostPropertyMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [models_1.PostPropertyMaster, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "updateAll", null);
tslib_1.__decorate([
    (0, rest_1.get)('/post-property-masters/{id}'),
    (0, rest_1.response)(200, {
        description: 'PostPropertyMaster model instance',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.param.filter(models_1.PostPropertyMaster, { exclude: 'where' })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "findById", null);
tslib_1.__decorate([
    (0, rest_1.get)('/post-property-masters/recommended-all'),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", []),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "getRecommended", null);
tslib_1.__decorate([
    (0, rest_1.get)('/post-property-masters/recommended'),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", []),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "getRecommendedFromRecommendedLaunch", null);
tslib_1.__decorate([
    (0, rest_1.get)('/post-property-masters/best-value-all'),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", []),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "getBestValue", null);
tslib_1.__decorate([
    (0, rest_1.get)('/post-property-masters/best-value'),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", []),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "getBestpropertyFromBestLaunch", null);
tslib_1.__decorate([
    (0, rest_1.get)('/post-property-masters/new-launch'),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", []),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "getNewLaunchFromLaunchTable", null);
tslib_1.__decorate([
    (0, rest_1.get)('/post-property-masters/new-launch-all'),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", []),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "getAllNewLaunch", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/post-property-masters/{id}'),
    (0, rest_1.response)(200, {
        description: 'PostPropertyMaster PATCH success',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, (0, core_1.inject)(rest_1.RestBindings.Http.REQUEST)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "updateWithPhotos", null);
tslib_1.__decorate([
    (0, rest_1.put)('/post-property-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'PostPropertyMaster PUT success',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, (0, rest_1.requestBody)()),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, models_1.PostPropertyMaster]),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "replaceById", null);
tslib_1.__decorate([
    (0, rest_1.del)('/post-property-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'PostPropertyMaster DELETE success',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number]),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "deleteById", null);
tslib_1.__decorate([
    (0, rest_1.get)('/post-property-masters/published-active'),
    (0, rest_1.response)(200, {
        description: 'Published and active PostPropertyMaster model instances using simple query params',
    }),
    tslib_1.__param(0, rest_1.param.query.string('fkcityId')),
    tslib_1.__param(1, rest_1.param.query.number('fkpostType')),
    tslib_1.__param(2, rest_1.param.query.string('fklocalityId')),
    tslib_1.__param(3, rest_1.param.query.number('fkpropertytypeId')),
    tslib_1.__param(4, rest_1.param.query.number('fkfurnishingtypeId')),
    tslib_1.__param(5, rest_1.param.query.number('fktransactionId')),
    tslib_1.__param(6, rest_1.param.query.number('fkpossessionId')),
    tslib_1.__param(7, rest_1.param.query.number('fkfacingId')),
    tslib_1.__param(8, rest_1.param.query.number('fkmainpropertytypeId')),
    tslib_1.__param(9, rest_1.param.query.number('fkuserId')),
    tslib_1.__param(10, rest_1.param.query.number('RERA_is_active')),
    tslib_1.__param(11, rest_1.param.query.string('Property_Title')),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [String, Number, String, Number, Number, Number, Number, Number, Number, Number, Number, String]),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "getPublishedActive", null);
tslib_1.__decorate([
    (0, rest_1.get)('/post-property-masters/published-active/{id}'),
    (0, rest_1.response)(200, {
        description: 'Published and active PostPropertyMaster model instance by ID',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.param.filter(models_1.PostPropertyMaster, { exclude: 'where' })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PostpropertymasterController.prototype, "getPublishedActiveById", null);
exports.PostpropertymasterController = PostpropertymasterController = tslib_1.__decorate([
    tslib_1.__param(0, (0, repository_1.repository)(repositories_1.PostPropertyMasterRepository)),
    tslib_1.__param(1, (0, repository_1.repository)(repositories_1.RecommendedLaunchRepository)),
    tslib_1.__param(2, (0, repository_1.repository)(repositories_1.BestpropertyLaunchRepository)),
    tslib_1.__param(3, (0, repository_1.repository)(repositories_1.PostPropertyAmenitiesRepository)),
    tslib_1.__param(4, (0, repository_1.repository)(repositories_1.NewLaunchMasterRepository)),
    tslib_1.__metadata("design:paramtypes", [repositories_1.PostPropertyMasterRepository,
        repositories_1.RecommendedLaunchRepository,
        repositories_1.BestpropertyLaunchRepository,
        repositories_1.PostPropertyAmenitiesRepository,
        repositories_1.NewLaunchMasterRepository])
], PostpropertymasterController);
//# sourceMappingURL=postpropertymaster.controller.js.map