"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OurpartnermasterController = 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 = 'http://localhost:3001/uploads/partner-images';
const BASE_URL = `${constants_1.URL}/uploads/partner-images`;
const FALLBACK_URL = `${BASE_URL}/default.jpg`;
// ✅ helper function
function resolvePhoto(photo) {
    if (!photo)
        return FALLBACK_URL;
    if (photo.startsWith('http://') || photo.startsWith('https://')) {
        return photo.trim();
    }
    const filename = path_1.default.basename(photo);
    const localPath = path_1.default.join(__dirname, '../../uploads/partner-images', filename);
    if (fs_1.default.existsSync(localPath)) {
        return `${BASE_URL}/${filename}`;
    }
    return FALLBACK_URL;
}
let OurpartnermasterController = class OurpartnermasterController {
    constructor(ourPartnerMasterRepository) {
        this.ourPartnerMasterRepository = ourPartnerMasterRepository;
    }
    // 📌 upload middleware
    getMulterUpload() {
        const storage = multer_1.default.diskStorage({
            destination: (req, file, cb) => {
                const dir = path_1.default.join(__dirname, '../../uploads/partner-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 with photo upload
    async createWithPhoto(request) {
        const upload = this.getMulterUpload().single('photo');
        return new Promise((resolve, reject) => {
            upload(request, {}, async (err) => {
                if (err)
                    return reject(err);
                const file = request.file;
                const partner = await this.ourPartnerMasterRepository.create({
                    ...request.body,
                    partnerLogo: (file === null || file === void 0 ? void 0 : file.filename) || null,
                    createdAt: new Date().toISOString(),
                    lastChanged: new Date().toISOString(),
                    isActive: 1,
                });
                resolve(partner);
            });
        });
    }
    async create(ourPartnerMaster) {
        return this.ourPartnerMasterRepository.create(ourPartnerMaster);
    }
    async find(filter) {
        const data = await this.ourPartnerMasterRepository.find(filter);
        return data.map(item => ({
            ...item,
            partnerLogo: resolvePhoto(item.partnerLogo),
        }));
    }
    async findById(id, filter) {
        const item = await this.ourPartnerMasterRepository.findById(id, filter);
        return { ...item, photo: resolvePhoto(item.photo) };
    }
    async updateAll(ourPartnerMaster, where) {
        return this.ourPartnerMasterRepository.updateAll(ourPartnerMaster, where);
    }
    async updateById(id, ourPartnerMaster) {
        await this.ourPartnerMasterRepository.updateById(id, ourPartnerMaster);
    }
    async replaceById(id, ourPartnerMaster) {
        await this.ourPartnerMasterRepository.replaceById(id, ourPartnerMaster);
    }
    async deleteById(id) {
        await this.ourPartnerMasterRepository.deleteById(id);
    }
};
exports.OurpartnermasterController = OurpartnermasterController;
tslib_1.__decorate([
    (0, rest_1.post)('/our-partner-masters/uploads'),
    (0, rest_1.response)(200, {
        description: 'OurPartnerMaster with photo',
    }),
    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)
], OurpartnermasterController.prototype, "createWithPhoto", null);
tslib_1.__decorate([
    (0, rest_1.post)('/our-partner-masters'),
    (0, rest_1.response)(200, {
        description: 'OurPartnerMaster model instance',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.OurPartnerMaster) } },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.OurPartnerMaster, {
                    title: 'NewOurPartnerMaster',
                    exclude: ['partnerId'],
                }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], OurpartnermasterController.prototype, "create", null);
tslib_1.__decorate([
    (0, rest_1.get)('/our-partner-masters'),
    (0, rest_1.response)(200, {
        description: 'Array of OurPartnerMaster model instances',
    }),
    tslib_1.__param(0, rest_1.param.filter(models_1.OurPartnerMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], OurpartnermasterController.prototype, "find", null);
tslib_1.__decorate([
    (0, rest_1.get)('/our-partner-masters/{id}'),
    (0, rest_1.response)(200, {
        description: 'OurPartnerMaster model instance',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.param.filter(models_1.OurPartnerMaster, { exclude: 'where' })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], OurpartnermasterController.prototype, "findById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/our-partner-masters'),
    (0, rest_1.response)(200, {
        description: 'OurPartnerMaster 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.OurPartnerMaster, { partial: true }),
            },
        },
    })),
    tslib_1.__param(1, rest_1.param.where(models_1.OurPartnerMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [models_1.OurPartnerMaster, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], OurpartnermasterController.prototype, "updateAll", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/our-partner-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'OurPartnerMaster 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.OurPartnerMaster, { partial: true }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, models_1.OurPartnerMaster]),
    tslib_1.__metadata("design:returntype", Promise)
], OurpartnermasterController.prototype, "updateById", null);
tslib_1.__decorate([
    (0, rest_1.put)('/our-partner-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'OurPartnerMaster 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.OurPartnerMaster]),
    tslib_1.__metadata("design:returntype", Promise)
], OurpartnermasterController.prototype, "replaceById", null);
tslib_1.__decorate([
    (0, rest_1.del)('/our-partner-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'OurPartnerMaster 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)
], OurpartnermasterController.prototype, "deleteById", null);
exports.OurpartnermasterController = OurpartnermasterController = tslib_1.__decorate([
    tslib_1.__param(0, (0, repository_1.repository)(repositories_1.OurPartnerMasterRepository)),
    tslib_1.__metadata("design:paramtypes", [repositories_1.OurPartnerMasterRepository])
], OurpartnermasterController);
//# sourceMappingURL=ourpartnermaster.controller.js.map