"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TestimonialmasterController = 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 BASE_URL = `${constants_1.URL}/uploads/testimonial-images`;
// const BASE_URL = `${URL}/uploads/testimonial-images`
const FALLBACK_URL = `${BASE_URL}/default.jpg`;
// ✅ helper
function resolveImage(image) {
    if (!image)
        return FALLBACK_URL;
    if (image.startsWith('http://') || image.startsWith('https://')) {
        return image.trim();
    }
    const filename = path_1.default.basename(image);
    const localPath = path_1.default.join(__dirname, '../../uploads/testimonial-images', filename);
    if (fs_1.default.existsSync(localPath)) {
        return `${BASE_URL}/${filename}`;
    }
    return FALLBACK_URL;
}
let TestimonialmasterController = class TestimonialmasterController {
    constructor(testimonialMasterRepository) {
        this.testimonialMasterRepository = testimonialMasterRepository;
    }
    // 📌 multer upload middleware
    getMulterUpload() {
        const storage = multer_1.default.diskStorage({
            destination: (req, file, cb) => {
                const dir = path_1.default.join(__dirname, '../../uploads/testimonial-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 });
    }
    // ✅ Upload endpoint: create with profile + property image
    async createWithImages(request) {
        const upload = this.getMulterUpload().fields([
            { name: 'profileImage', maxCount: 1 },
            { name: 'propertyImage', maxCount: 1 },
        ]);
        return new Promise((resolve, reject) => {
            upload(request, {}, async (err) => {
                var _a, _b, _c, _d;
                if (err)
                    return reject(err);
                const files = request.files;
                const testimonial = await this.testimonialMasterRepository.create({
                    ...request.body,
                    profileImage: ((_b = (_a = files === null || files === void 0 ? void 0 : files.profileImage) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.filename) || null,
                    propertyImage: ((_d = (_c = files === null || files === void 0 ? void 0 : files.propertyImage) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.filename) || null,
                    lastChanged: new Date().toISOString(),
                    createdAt: new Date().toISOString(),
                });
                resolve(testimonial);
            });
        });
    }
    // ✅ Normal create (no upload)
    async create(testimonialMaster) {
        return this.testimonialMasterRepository.create(testimonialMaster);
    }
    async find(filter) {
        const data = await this.testimonialMasterRepository.find(filter);
        return data.map(item => ({
            ...item,
            profileImage: resolveImage(item.profileImage),
            propertyImage: resolveImage(item.propertyImage),
        }));
    }
    async findById(id, filter) {
        const item = await this.testimonialMasterRepository.findById(id, filter);
        return {
            ...item,
            profileImage: resolveImage(item.profileImage),
            propertyImage: resolveImage(item.propertyImage),
        };
    }
    async updateAll(testimonialMaster, where) {
        return this.testimonialMasterRepository.updateAll(testimonialMaster, where);
    }
    async updateById(id, testimonialMaster) {
        await this.testimonialMasterRepository.updateById(id, testimonialMaster);
    }
    async replaceById(id, testimonialMaster) {
        await this.testimonialMasterRepository.replaceById(id, testimonialMaster);
    }
    async deleteById(id) {
        await this.testimonialMasterRepository.deleteById(id);
    }
};
exports.TestimonialmasterController = TestimonialmasterController;
tslib_1.__decorate([
    (0, rest_1.post)('/testimonial-masters/uploads'),
    (0, rest_1.response)(200, {
        description: 'TestimonialMaster with images',
    }),
    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)
], TestimonialmasterController.prototype, "createWithImages", null);
tslib_1.__decorate([
    (0, rest_1.post)('/testimonial-masters'),
    (0, rest_1.response)(200, {
        description: 'TestimonialMaster model instance',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.TestimonialMaster) } },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.TestimonialMaster, {
                    title: 'NewTestimonialMaster',
                    exclude: ['testimonialId'],
                }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], TestimonialmasterController.prototype, "create", null);
tslib_1.__decorate([
    (0, rest_1.get)('/testimonial-masters'),
    (0, rest_1.response)(200, {
        description: 'Array of TestimonialMaster model instances',
    }),
    tslib_1.__param(0, rest_1.param.filter(models_1.TestimonialMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], TestimonialmasterController.prototype, "find", null);
tslib_1.__decorate([
    (0, rest_1.get)('/testimonial-masters/{id}'),
    (0, rest_1.response)(200, {
        description: 'TestimonialMaster model instance',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.param.filter(models_1.TestimonialMaster, { exclude: 'where' })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], TestimonialmasterController.prototype, "findById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/testimonial-masters'),
    (0, rest_1.response)(200, {
        description: 'TestimonialMaster 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.TestimonialMaster, { partial: true }),
            },
        },
    })),
    tslib_1.__param(1, rest_1.param.where(models_1.TestimonialMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [models_1.TestimonialMaster, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], TestimonialmasterController.prototype, "updateAll", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/testimonial-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'TestimonialMaster 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.TestimonialMaster, { partial: true }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, models_1.TestimonialMaster]),
    tslib_1.__metadata("design:returntype", Promise)
], TestimonialmasterController.prototype, "updateById", null);
tslib_1.__decorate([
    (0, rest_1.put)('/testimonial-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'TestimonialMaster 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.TestimonialMaster]),
    tslib_1.__metadata("design:returntype", Promise)
], TestimonialmasterController.prototype, "replaceById", null);
tslib_1.__decorate([
    (0, rest_1.del)('/testimonial-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'TestimonialMaster 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)
], TestimonialmasterController.prototype, "deleteById", null);
exports.TestimonialmasterController = TestimonialmasterController = tslib_1.__decorate([
    tslib_1.__param(0, (0, repository_1.repository)(repositories_1.TestimonialMasterRepository)),
    tslib_1.__metadata("design:paramtypes", [repositories_1.TestimonialMasterRepository])
], TestimonialmasterController);
//# sourceMappingURL=testimonialmaster.controller.js.map