"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LogomasterController = 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");
let LogomasterController = class LogomasterController {
    constructor(logoMasterRepository) {
        this.logoMasterRepository = logoMasterRepository;
        this.uploadPath = path_1.default.resolve(process.cwd(), 'uploads/logos');
        if (!fs_1.default.existsSync(this.uploadPath)) {
            fs_1.default.mkdirSync(this.uploadPath, { recursive: true });
        }
        this.storage = multer_1.default.diskStorage({
            destination: (_req, _file, cb) => cb(null, this.uploadPath),
            filename: (_req, file, cb) => {
                const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
                cb(null, uniqueSuffix + path_1.default.extname(file.originalname));
            },
        });
        this.upload = (0, multer_1.default)({
            storage: this.storage,
            limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
        }).single('logoImage');
    }
    /** CREATE with file upload */
    async create(req) {
        return new Promise((resolve, reject) => {
            this.upload(req, {}, async (err) => {
                if (err)
                    return reject(err);
                const body = req.body;
                if (req.file) {
                    // ✅ Save only filename
                    body.logoImage = req.file.filename;
                }
                try {
                    const created = await this.logoMasterRepository.create(body);
                    resolve(created);
                }
                catch (e) {
                    reject(e);
                }
            });
        });
    }
    /** GET all with full URL */
    async find() {
        const logos = await this.logoMasterRepository.find();
        return logos.map(logo => ({
            ...logo,
            logoImage: logo.logoImage
                ? `${constants_1.URL}/uploads/logos/${logo.logoImage}`
                : null
        }));
    }
    /** GET by ID */
    async findById(id, filter) {
        return this.logoMasterRepository.findById(id, filter);
    }
    /** UPDATE by ID with optional file upload */
    async updateById(req, id) {
        return new Promise((resolve, reject) => {
            this.upload(req, {}, async (err) => {
                if (err)
                    return reject(err);
                const body = req.body;
                if (req.file) {
                    // Delete old file if exists
                    const existing = await this.logoMasterRepository.findById(id);
                    if (existing.logoImage) {
                        const oldPath = path_1.default.resolve(this.uploadPath, existing.logoImage);
                        if (fs_1.default.existsSync(oldPath)) {
                            fs_1.default.unlinkSync(oldPath);
                        }
                    }
                    body.logoImage = req.file.filename;
                }
                await this.logoMasterRepository.updateById(id, body);
                resolve();
            });
        });
    }
    /** DELETE by ID and remove file */
    async deleteById(id) {
        const existing = await this.logoMasterRepository.findById(id);
        if (existing.logoImage) {
            const filePath = path_1.default.resolve(this.uploadPath, existing.logoImage);
            if (fs_1.default.existsSync(filePath)) {
                fs_1.default.unlinkSync(filePath);
            }
        }
        await this.logoMasterRepository.deleteById(id);
    }
};
exports.LogomasterController = LogomasterController;
tslib_1.__decorate([
    (0, rest_1.post)('/logo-masters'),
    (0, rest_1.response)(200, {
        description: 'LogoMaster model instance',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.LogoMaster) } },
    }),
    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)
], LogomasterController.prototype, "create", null);
tslib_1.__decorate([
    (0, rest_1.get)('/logo-masters'),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", []),
    tslib_1.__metadata("design:returntype", Promise)
], LogomasterController.prototype, "find", null);
tslib_1.__decorate([
    (0, rest_1.get)('/logo-masters/{id}'),
    (0, rest_1.response)(200, {
        description: 'LogoMaster model instance',
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.LogoMaster, { includeRelations: true }),
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.param.filter(models_1.LogoMaster, { exclude: 'where' })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], LogomasterController.prototype, "findById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/logo-masters/{id}'),
    (0, rest_1.response)(204, { description: 'LogoMaster PATCH success' }),
    tslib_1.__param(0, (0, core_1.inject)(rest_1.RestBindings.Http.REQUEST)),
    tslib_1.__param(1, rest_1.param.path.number('id')),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object, Number]),
    tslib_1.__metadata("design:returntype", Promise)
], LogomasterController.prototype, "updateById", null);
tslib_1.__decorate([
    (0, rest_1.del)('/logo-masters/{id}'),
    (0, rest_1.response)(204, { description: 'LogoMaster 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)
], LogomasterController.prototype, "deleteById", null);
exports.LogomasterController = LogomasterController = tslib_1.__decorate([
    tslib_1.__param(0, (0, repository_1.repository)(repositories_1.LogoMasterRepository)),
    tslib_1.__metadata("design:paramtypes", [repositories_1.LogoMasterRepository])
], LogomasterController);
//# sourceMappingURL=logomaster.controller.js.map