"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.PackageMasterController = void 0;
const tslib_1 = require("tslib");
/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/no-shadow */
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;
// --------- Configure Upload Directory ----------
const uploadDir = path_1.default.join(__dirname, '../../uploads/packages');
if (!fs_1.default.existsSync(uploadDir)) {
    fs_1.default.mkdirSync(uploadDir, { recursive: true });
}
const storage = multer_1.default.diskStorage({
    destination: function (_req, _file, cb) {
        cb(null, uploadDir);
    },
    filename: function (_req, file, cb) {
        // Generate a unique filename with original extension
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        const ext = path_1.default.extname(file.originalname);
        cb(null, `package-${uniqueSuffix}${ext}`);
    },
});
const upload = (0, multer_1.default)({ storage });
let PackageMasterController = class PackageMasterController {
    constructor(packageMasterRepository) {
        this.packageMasterRepository = packageMasterRepository;
    }
    // ---------- CREATE without image ----------
    async create(packageMaster) {
        return this.packageMasterRepository.create(packageMaster);
    }
    // ---------- CREATE with image ----------
    async createWithFile(request, response) {
        return new Promise((resolve, reject) => {
            // eslint-disable-next-line @typescript-eslint/no-misused-promises
            upload.single('packagePhoto')(request, response, async (err) => {
                if (err)
                    return reject(err);
                const file = request.file;
                const fields = request.body;
                try {
                    const newPackage = await this.packageMasterRepository.create({
                        fkusertypeId: parseInt(fields.fkusertypeId),
                        packageName: fields.packageName,
                        packageDescription: fields.packageDescription,
                        packageduration: fields.packageduration ? parseInt(fields.packageduration) : undefined,
                        packageCost: fields.packageCost ? parseFloat(fields.packageCost) : undefined,
                        propertyVisit: fields.propertyVisit ? parseInt(fields.propertyVisit) : undefined,
                        propertyAddToCart: fields.propertyAddToCart ? parseInt(fields.propertyAddToCart) : undefined,
                        isDefault: fields.isDefault ? parseInt(fields.isDefault) : 1,
                        isOn: fields.isOn ? parseInt(fields.isOn) : 1,
                        isActive: fields.isActive ? parseInt(fields.isActive) : 1,
                        packagePhoto: file ? `${BASE_URL}/uploads/packages/${file.filename}` : undefined,
                        createdDate: new Date().toISOString(),
                        createdBy: fields.createdBy ? parseInt(fields.createdBy) : undefined,
                        lastChanged: new Date().toISOString(),
                    });
                    resolve(newPackage);
                }
                catch (e) {
                    reject(e);
                }
            });
        });
    }
    // ---------- COUNT ----------
    async count(where) {
        return this.packageMasterRepository.count(where);
    }
    // ---------- FIND ----------
    async find(filter) {
        return this.packageMasterRepository.find({
            ...filter,
            include: [{
                    relation: 'usertype',
                    scope: {
                        fields: {
                            userId: true,
                            username: true,
                        },
                    },
                }],
        });
    }
    // ---------- FIND BY ID ----------
    async findById(id, filter) {
        return this.packageMasterRepository.findById(id, {
            ...filter,
            include: [{
                    relation: 'usertype',
                    scope: {
                        fields: {
                            userId: true,
                            username: true,
                        },
                    },
                }],
        });
    }
    // ---------- Standard UPDATE (without image) - JSON only ----------
    async updateById(id, packageMaster) {
        await this.packageMasterRepository.updateById(id, {
            ...packageMaster,
            lastChanged: new Date().toISOString(),
        });
    }
    // ---------- UPDATE with image (multipart/form-data) ----------
    async updateByIdWithFile(id, request, response) {
        return new Promise((resolve, reject) => {
            // eslint-disable-next-line @typescript-eslint/no-misused-promises
            upload.single('packagePhoto')(request, response, async (err) => {
                if (err)
                    return reject(err);
                const file = request.file;
                const fields = request.body;
                try {
                    // Get existing record
                    const existingPackage = await this.packageMasterRepository.findById(id);
                    // If there's an old photo and a new one is uploaded, delete the old one
                    if (file && existingPackage.packagePhoto) {
                        const oldPhotoPath = existingPackage.packagePhoto.replace(`${BASE_URL}/uploads/packages/`, '');
                        const fullOldPath = path_1.default.join(uploadDir, oldPhotoPath);
                        if (fs_1.default.existsSync(fullOldPath)) {
                            fs_1.default.unlinkSync(fullOldPath);
                        }
                    }
                    // Determine the photo value
                    let photoValue;
                    if (file) {
                        // New file uploaded
                        photoValue = `${BASE_URL}/uploads/packages/${file.filename}`;
                    }
                    else if (fields.packagePhoto === 'null' || fields.packagePhoto === '' || fields.packagePhoto === null) {
                        // Explicitly delete the photo
                        photoValue = undefined;
                        // Delete the existing file if any
                        if (existingPackage.packagePhoto) {
                            const oldPhotoPath = existingPackage.packagePhoto.replace(`${BASE_URL}/uploads/packages/`, '');
                            const fullOldPath = path_1.default.join(uploadDir, oldPhotoPath);
                            if (fs_1.default.existsSync(fullOldPath)) {
                                fs_1.default.unlinkSync(fullOldPath);
                            }
                        }
                    }
                    else {
                        // Keep existing photo
                        photoValue = existingPackage.packagePhoto;
                    }
                    await this.packageMasterRepository.updateById(id, {
                        fkusertypeId: fields.fkusertypeId ? parseInt(fields.fkusertypeId) : existingPackage.fkusertypeId,
                        packageName: fields.packageName || existingPackage.packageName,
                        packageDescription: fields.packageDescription || existingPackage.packageDescription,
                        packageduration: fields.packageduration ? parseInt(fields.packageduration) : existingPackage.packageduration,
                        packageCost: fields.packageCost ? parseFloat(fields.packageCost) : existingPackage.packageCost,
                        propertyVisit: fields.propertyVisit ? parseInt(fields.propertyVisit) : existingPackage.propertyVisit,
                        propertyAddToCart: fields.propertyAddToCart ? parseInt(fields.propertyAddToCart) : existingPackage.propertyAddToCart,
                        isDefault: fields.isDefault ? parseInt(fields.isDefault) : existingPackage.isDefault,
                        isOn: fields.isOn ? parseInt(fields.isOn) : existingPackage.isOn,
                        isActive: fields.isActive ? parseInt(fields.isActive) : existingPackage.isActive,
                        packagePhoto: photoValue,
                        modifiedDate: new Date().toISOString(),
                        modifiedBy: fields.modifiedBy ? parseInt(fields.modifiedBy) : existingPackage.modifiedBy,
                        lastChanged: new Date().toISOString(),
                    });
                    resolve();
                }
                catch (e) {
                    reject(e);
                }
            });
        });
    }
    // ---------- REPLACE ----------
    async replaceById(id, packageMaster) {
        await this.packageMasterRepository.replaceById(id, {
            ...packageMaster,
            lastChanged: new Date().toISOString(),
        });
    }
    // ---------- DELETE ----------
    async deleteById(id) {
        // Get the package to delete the associated photo
        const packageToDelete = await this.packageMasterRepository.findById(id);
        // Delete the photo file if it exists
        if (packageToDelete.packagePhoto) {
            const photoPath = packageToDelete.packagePhoto.replace(`${BASE_URL}/uploads/packages/`, '');
            const fullPath = path_1.default.join(uploadDir, photoPath);
            if (fs_1.default.existsSync(fullPath)) {
                fs_1.default.unlinkSync(fullPath);
            }
        }
        // Delete the record from the database
        await this.packageMasterRepository.deleteById(id);
    }
    // ---------- SOFT DELETE ----------
    async softDeletePackage(id, deleteData) {
        await this.packageMasterRepository.updateById(id, {
            isActive: 0,
            deletedDate: new Date().toISOString(),
            deletedBy: deleteData === null || deleteData === void 0 ? void 0 : deleteData.deletedBy,
            deleteRemark: deleteData === null || deleteData === void 0 ? void 0 : deleteData.deleteRemark,
            lastChanged: new Date().toISOString(),
        });
    }
};
exports.PackageMasterController = PackageMasterController;
tslib_1.__decorate([
    (0, rest_1.post)('/package-masters/json'),
    (0, rest_1.response)(200, {
        description: 'PackageMaster model instance',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.PackageMaster) } },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.PackageMaster, {
                    title: 'NewPackageMaster',
                    exclude: ['packageId'],
                }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PackageMasterController.prototype, "create", null);
tslib_1.__decorate([
    (0, rest_1.post)('/package-masters'),
    (0, rest_1.response)(200, {
        description: 'Create package with image',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.PackageMaster) } },
    }),
    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)
], PackageMasterController.prototype, "createWithFile", null);
tslib_1.__decorate([
    (0, rest_1.get)('/package-masters/count'),
    (0, rest_1.response)(200, {
        description: 'PackageMaster model count',
        content: { 'application/json': { schema: repository_1.CountSchema } },
    }),
    tslib_1.__param(0, rest_1.param.where(models_1.PackageMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PackageMasterController.prototype, "count", null);
tslib_1.__decorate([
    (0, rest_1.get)('/package-masters'),
    (0, rest_1.response)(200, {
        description: 'Array of PackageMaster model instances',
        content: {
            'application/json': {
                schema: {
                    type: 'array',
                    items: (0, rest_1.getModelSchemaRef)(models_1.PackageMaster, { includeRelations: true }),
                },
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.filter(models_1.PackageMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PackageMasterController.prototype, "find", null);
tslib_1.__decorate([
    (0, rest_1.get)('/package-masters/{id}'),
    (0, rest_1.response)(200, {
        description: 'PackageMaster model instance',
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.PackageMaster, { includeRelations: true }),
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.param.filter(models_1.PackageMaster, { exclude: 'where' })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PackageMasterController.prototype, "findById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/package-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'PackageMaster PATCH success (JSON only)',
    }),
    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.PackageMaster, { partial: true }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, models_1.PackageMaster]),
    tslib_1.__metadata("design:returntype", Promise)
], PackageMasterController.prototype, "updateById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/package-masters/with-image/{id}'),
    (0, rest_1.response)(204, {
        description: 'PackageMaster PATCH success with image upload',
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.requestBody.file()),
    tslib_1.__param(2, (0, core_1.inject)(rest_1.RestBindings.Http.RESPONSE)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PackageMasterController.prototype, "updateByIdWithFile", null);
tslib_1.__decorate([
    (0, rest_1.put)('/package-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'PackageMaster 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.PackageMaster]),
    tslib_1.__metadata("design:returntype", Promise)
], PackageMasterController.prototype, "replaceById", null);
tslib_1.__decorate([
    (0, rest_1.del)('/package-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'PackageMaster 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)
], PackageMasterController.prototype, "deleteById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/package-masters/soft-delete/{id}'),
    (0, rest_1.response)(204, {
        description: 'PackageMaster soft delete 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, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], PackageMasterController.prototype, "softDeletePackage", null);
exports.PackageMasterController = PackageMasterController = tslib_1.__decorate([
    tslib_1.__param(0, (0, repository_1.repository)(repositories_1.PackageMasterRepository)),
    tslib_1.__metadata("design:paramtypes", [repositories_1.PackageMasterRepository])
], PackageMasterController);
//# sourceMappingURL=package-master.controller.js.map