"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdsManagementController = 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;
// --------- Configure Upload Directory ----------
const uploadDir = path_1.default.join(__dirname, '../../uploads/ads');
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) {
        cb(null, `${Date.now()}-${file.originalname}`);
    },
});
const upload = (0, multer_1.default)({ storage });
let AdsManagementController = class AdsManagementController {
    constructor(adsManagementRepository) {
        this.adsManagementRepository = adsManagementRepository;
    }
    // ---------- CREATE with image ----------
    async createWithFile(request, response) {
        return new Promise((resolve, reject) => {
            // eslint-disable-next-line @typescript-eslint/no-misused-promises
            upload.single('adsPhoto')(request, response, async (err) => {
                if (err)
                    return reject(err);
                const file = request.file;
                const fields = request.body;
                try {
                    const newAd = await this.adsManagementRepository.create({
                        adsTitle: fields.adsTitle,
                        publish_Fag: 1,
                        fksellerId: parseInt(fields.fksellerId),
                        fkadsTypeId: parseInt(fields.fkadsTypeId),
                        adsStartDate: fields.adsStartDate ? new Date(fields.adsStartDate) : undefined,
                        adsEndDate: fields.adsEndDate ? new Date(fields.adsEndDate) : undefined,
                        adsPhoto: file ? `${BASE_URL}/uploads/ads/${file.filename}` : undefined,
                        lastChanged: new Date().toISOString(),
                    });
                    resolve(newAd);
                }
                catch (e) {
                    reject(e);
                }
            });
        });
    }
    // ---------- COUNT ----------
    async count(where) {
        return this.adsManagementRepository.count(where);
    }
    // ---------- FIND ----------
    async find(filter) {
        return this.adsManagementRepository.find({
            ...filter,
            include: [
                {
                    relation: 'adsType',
                    scope: {
                        fields: {
                            adsTypeId: true,
                            adstypeName: true,
                        },
                    },
                },
            ],
        });
    }
    // ---------- FIND BY ID ----------
    async findById(id, filter) {
        return this.adsManagementRepository.findById(id, {
            ...filter,
            include: [
                {
                    relation: 'adsType',
                    scope: {
                        fields: {
                            adsTypeId: true,
                            adstypeName: true,
                        },
                    },
                },
            ],
        });
    }
    // ---------- UPDATE with image ----------
    async updateByIdWithFile(id, request, response) {
        return new Promise((resolve, reject) => {
            // eslint-disable-next-line @typescript-eslint/no-misused-promises
            upload.single('adsPhoto')(request, response, async (err) => {
                if (err)
                    return reject(err);
                const file = request.file;
                const fields = request.body;
                try {
                    // Get existing record
                    const existingAd = await this.adsManagementRepository.findById(id);
                    await this.adsManagementRepository.updateById(id, {
                        adsTitle: fields.adsTitle,
                        publish_Fag: 1,
                        fksellerId: parseInt(fields.fksellerId),
                        fkadsTypeId: parseInt(fields.fkadsTypeId),
                        adsStartDate: fields.adsStartDate || null,
                        adsEndDate: fields.adsEndDate || null,
                        adsPhoto: file
                            ? `${BASE_URL}/uploads/ads/${file.filename}`
                            : existingAd.adsPhoto,
                        lastChanged: new Date().toISOString(),
                    });
                    resolve();
                }
                catch (e) {
                    reject(e);
                }
            });
        });
    }
    // ---------- DELETE ----------
    async deleteById(id) {
        await this.adsManagementRepository.deleteById(id);
    }
    async softDeleteAd(id) {
        await this.adsManagementRepository.updateById(id, {
            isActive: 0,
            lastChanged: new Date().toISOString(),
        });
    }
};
exports.AdsManagementController = AdsManagementController;
tslib_1.__decorate([
    (0, rest_1.post)('/ads-managements'),
    (0, rest_1.response)(200, {
        description: 'Create ad with image',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.AdsManagement) } },
    }),
    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)
], AdsManagementController.prototype, "createWithFile", null);
tslib_1.__decorate([
    (0, rest_1.get)('/ads-managements/count'),
    (0, rest_1.response)(200, {
        description: 'AdsManagement model count',
        content: { 'application/json': { schema: repository_1.CountSchema } },
    }),
    tslib_1.__param(0, rest_1.param.where(models_1.AdsManagement)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], AdsManagementController.prototype, "count", null);
tslib_1.__decorate([
    (0, rest_1.get)('/ads-managements'),
    (0, rest_1.response)(200, {
        description: 'Array of AdsManagement model instances',
        content: {
            'application/json': {
                schema: {
                    type: 'array',
                    items: (0, rest_1.getModelSchemaRef)(models_1.AdsManagement, { includeRelations: true }),
                },
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.filter(models_1.AdsManagement)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], AdsManagementController.prototype, "find", null);
tslib_1.__decorate([
    (0, rest_1.get)('/ads-managements/{id}'),
    (0, rest_1.response)(200, {
        description: 'AdsManagement model instance',
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.AdsManagement, { includeRelations: true }),
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.param.filter(models_1.AdsManagement, { exclude: 'where' })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], AdsManagementController.prototype, "findById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/ads-managements/{id}'),
    (0, rest_1.response)(204, {
        description: 'AdsManagement PATCH success',
    }),
    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)
], AdsManagementController.prototype, "updateByIdWithFile", null);
tslib_1.__decorate([
    (0, rest_1.del)('/ads-managements/{id}'),
    (0, rest_1.response)(204, {
        description: 'AdsManagement 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)
], AdsManagementController.prototype, "deleteById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/ads-managements/soft-delete/{id}'),
    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)
], AdsManagementController.prototype, "softDeleteAd", null);
exports.AdsManagementController = AdsManagementController = tslib_1.__decorate([
    tslib_1.__param(0, (0, repository_1.repository)(repositories_1.AdsManagementRepository)),
    tslib_1.__metadata("design:paramtypes", [repositories_1.AdsManagementRepository])
], AdsManagementController);
//# sourceMappingURL=ads-management.controller.js.map