"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RealestetemasterController = void 0;
const tslib_1 = require("tslib");
const core_1 = require("@loopback/core");
const repository_1 = require("@loopback/repository");
const rest_1 = require("@loopback/rest");
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 constants_1 = require("../config/constants");
const models_1 = require("../models");
const repositories_1 = require("../repositories");
const uploadDir = path_1.default.join(__dirname, '../../uploads/real-estate-images');
if (!fs_1.default.existsSync(uploadDir)) {
    fs_1.default.mkdirSync(uploadDir, { recursive: true });
}
const BASE_URL = `${constants_1.URL}/uploads/real-estate-images`;
const FALLBACK_URL = `${BASE_URL}/default.jpg`;
let RealestetemasterController = class RealestetemasterController {
    constructor(realEstateMasterRepository) {
        this.realEstateMasterRepository = realEstateMasterRepository;
    }
    /**
     * ✅ Create real estate with only JSON (no file)
     */
    async create(realEstateMaster) {
        return this.realEstateMasterRepository.create(realEstateMaster);
    }
    /**
     * ✅ Create real estate with image upload (multipart/form-data)
     */
    async createWithImage(request, response) {
        return new Promise((resolve, reject) => {
            const storage = multer_1.default.diskStorage({
                destination: function (_req, _file, cb) {
                    cb(null, uploadDir);
                },
                filename: function (_req, file, cb) {
                    cb(null, `${Date.now()}-${file.originalname}`);
                },
            });
            const upload = (0, multer_1.default)({ storage }).single('blogImage'); // frontend must send `blogImage`
            upload(request, response, async (err) => {
                if (err)
                    return reject(err);
                const body = request.body;
                const file = request.file;
                try {
                    const newEstate = await this.realEstateMasterRepository.create({
                        blogTitle: body.blogTitle,
                        blogDescription: body.blogDescription,
                        blogStartAmount: body.blogStartAmount,
                        blogEndAmount: body.blogEndAmount,
                        blogDate: body.blogDate,
                        blogImage: file ? file.filename : null,
                        lastChanged: new Date().toISOString(),
                        createdAt: new Date().toISOString()
                    });
                    resolve({
                        success: true,
                        data: newEstate,
                        imageUrl: file ? `${BASE_URL}/${file.filename}` : FALLBACK_URL,
                    });
                }
                catch (e) {
                    reject(e);
                }
            });
        });
    }
    /**
     * ✅ Fetch all with image URL resolution
     */
    async find(filter) {
        const data = await this.realEstateMasterRepository.find({
            ...filter,
            order: ['created_date DESC'],
        });
        return data.map(item => {
            var _a;
            let imageUrl = (_a = item.blogImage) === null || _a === void 0 ? void 0 : _a.trim();
            if (imageUrl && (imageUrl.startsWith('http://') || imageUrl.startsWith('https://'))) {
                return { ...item, blogImage: imageUrl };
            }
            if (imageUrl) {
                const filename = path_1.default.basename(imageUrl);
                const localPath = path_1.default.join(uploadDir, filename);
                if (fs_1.default.existsSync(localPath)) {
                    return { ...item, blogImage: `${BASE_URL}/${filename}` };
                }
            }
            return { ...item, blogImage: FALLBACK_URL };
        });
    }
    async count(where) {
        return this.realEstateMasterRepository.count(where);
    }
    // @get('/real-estate-masters')
    // @response(200, {
    //   description: 'Array of RealEstateMaster model instances',
    //   content: {
    //     'application/json': {
    //       schema: {
    //         type: 'array',
    //         items: getModelSchemaRef(RealEstateMaster, {includeRelations: true}),
    //       },
    //     },
    //   },
    // })
    // async find(
    //   @param.filter(RealEstateMaster) filter?: Filter<RealEstateMaster>,
    // ): Promise<RealEstateMaster[]> {
    //   return this.realEstateMasterRepository.find(filter);
    // }
    // @get('/real-estate-masters')
    // @response(200, {
    //   description: 'Array of RealEstateMaster model instances',
    //   content: {
    //     'application/json': {
    //       schema: {
    //         type: 'array',
    //         items: getModelSchemaRef(RealEstateMaster, {includeRelations: true}),
    //       },
    //     },
    //   },
    // })
    // async find(
    //   @param.filter(RealEstateMaster) filter?: Filter<RealEstateMaster>,
    // ): Promise<any[]> {
    //   const data = await this.realEstateMasterRepository.find({
    //     ...filter,
    //     order: ['created_date DESC'],
    //   });
    //   return data.map(item => {
    //     let imageUrl = item.blogImage?.trim();
    //     // ✅ Case 1: Already a live URL (Unsplash, etc.)
    //     if (imageUrl && (imageUrl.startsWith('http://') || imageUrl.startsWith('https://'))) {
    //       return {
    //         ...item,
    //         blogImage: imageUrl,
    //       };
    //     }
    //     // ✅ Case 2: Local image (stored filename like "1755673228599-partner1.avif")
    //     if (imageUrl) {
    //       const filename = path.basename(imageUrl);
    //       const localPath = path.join(__dirname, '../../uploads/real-estate-images', filename);
    //       if (fs.existsSync(localPath)) {
    //         return {
    //           ...item,
    //           blogImage: `${BASE_URL}/${filename}`,
    //         };
    //       }
    //     }
    //     // ✅ Case 3: Nothing found → fallback
    //     return {
    //       ...item,
    //       blogImage: FALLBACK_URL,
    //     };
    //   });
    // }
    async updateAll(realEstateMaster, where) {
        return this.realEstateMasterRepository.updateAll(realEstateMaster, where);
    }
    async findById(id, filter) {
        return this.realEstateMasterRepository.findById(id, filter);
    }
    async updateById(id, realEstateMaster) {
        await this.realEstateMasterRepository.updateById(id, realEstateMaster);
    }
    async replaceById(id, realEstateMaster) {
        await this.realEstateMasterRepository.replaceById(id, realEstateMaster);
    }
    async deleteById(id) {
        await this.realEstateMasterRepository.deleteById(id);
    }
};
exports.RealestetemasterController = RealestetemasterController;
tslib_1.__decorate([
    (0, rest_1.post)('/real-estate-masters'),
    (0, rest_1.response)(200, {
        description: 'RealEstateMaster model instance',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.RealEstateMaster) } },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.RealEstateMaster, {
                    title: 'NewRealEstateMaster',
                    exclude: ['blogId'],
                }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], RealestetemasterController.prototype, "create", null);
tslib_1.__decorate([
    (0, rest_1.post)('/real-estate-masters/upload'),
    (0, rest_1.response)(200, {
        description: 'RealEstateMaster model instance with image upload',
    }),
    tslib_1.__param(0, rest_1.requestBody.file()),
    tslib_1.__param(1, (0, core_1.inject)(rest_1.RestBindings.Http.RESPONSE)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], RealestetemasterController.prototype, "createWithImage", null);
tslib_1.__decorate([
    (0, rest_1.get)('/real-estate-masters'),
    (0, rest_1.response)(200, {
        description: 'Array of RealEstateMaster model instances',
        content: {
            'application/json': {
                schema: {
                    type: 'array',
                    items: (0, rest_1.getModelSchemaRef)(models_1.RealEstateMaster, { includeRelations: true }),
                },
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.filter(models_1.RealEstateMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], RealestetemasterController.prototype, "find", null);
tslib_1.__decorate([
    (0, rest_1.get)('/real-estate-masters/count'),
    (0, rest_1.response)(200, {
        description: 'RealEstateMaster model count',
        content: { 'application/json': { schema: repository_1.CountSchema } },
    }),
    tslib_1.__param(0, rest_1.param.where(models_1.RealEstateMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], RealestetemasterController.prototype, "count", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/real-estate-masters'),
    (0, rest_1.response)(200, {
        description: 'RealEstateMaster 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.RealEstateMaster, { partial: true }),
            },
        },
    })),
    tslib_1.__param(1, rest_1.param.where(models_1.RealEstateMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [models_1.RealEstateMaster, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], RealestetemasterController.prototype, "updateAll", null);
tslib_1.__decorate([
    (0, rest_1.get)('/real-estate-masters/{id}'),
    (0, rest_1.response)(200, {
        description: 'RealEstateMaster model instance',
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.RealEstateMaster, { includeRelations: true }),
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.param.filter(models_1.RealEstateMaster, { exclude: 'where' })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], RealestetemasterController.prototype, "findById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/real-estate-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'RealEstateMaster PATCH success',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.RealEstateMaster, { partial: true }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, models_1.RealEstateMaster]),
    tslib_1.__metadata("design:returntype", Promise)
], RealestetemasterController.prototype, "updateById", null);
tslib_1.__decorate([
    (0, rest_1.put)('/real-estate-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'RealEstateMaster 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.RealEstateMaster]),
    tslib_1.__metadata("design:returntype", Promise)
], RealestetemasterController.prototype, "replaceById", null);
tslib_1.__decorate([
    (0, rest_1.del)('/real-estate-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'RealEstateMaster 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)
], RealestetemasterController.prototype, "deleteById", null);
exports.RealestetemasterController = RealestetemasterController = tslib_1.__decorate([
    tslib_1.__param(0, (0, repository_1.repository)(repositories_1.RealEstateMasterRepository)),
    tslib_1.__metadata("design:paramtypes", [repositories_1.RealEstateMasterRepository])
], RealestetemasterController);
//# sourceMappingURL=realestetemaster.controller.js.map