"use strict";
// import {
//   Count,
//   CountSchema,
//   Filter,
//   FilterExcludingWhere,
//   repository,
//   Where,
// } from '@loopback/repository';
// import {
//   del,
//   get,
//   getModelSchemaRef,
//   param,
//   patch,
//   post,
//   put,
//   requestBody,
//   response,
// } from '@loopback/rest';
// import {BuyerMaster} from '../models';
// import {BuyerMasterRepository} from '../repositories';
Object.defineProperty(exports, "__esModule", { value: true });
exports.BuyermasterController = void 0;
const tslib_1 = require("tslib");
// export class BuyermasterController {
//   constructor(
//     @repository(BuyerMasterRepository)
//     public buyerMasterRepository: BuyerMasterRepository,
//   ) { }
//   @post('/buyer-masters')
//   @response(200, {
//     description: 'BuyerMaster model instance',
//     content: {'application/json': {schema: getModelSchemaRef(BuyerMaster)}},
//   })
//   async create(
//     @requestBody({
//       content: {
//         'application/json': {
//           schema: getModelSchemaRef(BuyerMaster, {
//             title: 'NewBuyerMaster',
//             exclude: ['buyerId'],
//           }),
//         },
//       },
//     })
//     buyerMaster: Omit<BuyerMaster, 'buyerId'>,
//   ): Promise<BuyerMaster> {
//     return this.buyerMasterRepository.create(buyerMaster);
//   }
//   @get('/buyer-masters/count')
//   @response(200, {
//     description: 'BuyerMaster model count',
//     content: {'application/json': {schema: CountSchema}},
//   })
//   async count(
//     @param.where(BuyerMaster) where?: Where<BuyerMaster>,
//   ): Promise<Count> {
//     return this.buyerMasterRepository.count(where);
//   }
//   @get('/buyer-masters')
//   @response(200, {
//     description: 'Array of BuyerMaster model instances',
//     content: {
//       'application/json': {
//         schema: {
//           type: 'array',
//           items: getModelSchemaRef(BuyerMaster, {includeRelations: true}),
//         },
//       },
//     },
//   })
//   async find(
//     @param.filter(BuyerMaster) filter?: Filter<BuyerMaster>,
//   ): Promise<BuyerMaster[]> {
//     return this.buyerMasterRepository.find(filter);
//   }
//   @patch('/buyer-masters')
//   @response(200, {
//     description: 'BuyerMaster PATCH success count',
//     content: {'application/json': {schema: CountSchema}},
//   })
//   async updateAll(
//     @requestBody({
//       content: {
//         'application/json': {
//           schema: getModelSchemaRef(BuyerMaster, {partial: true}),
//         },
//       },
//     })
//     buyerMaster: BuyerMaster,
//     @param.where(BuyerMaster) where?: Where<BuyerMaster>,
//   ): Promise<Count> {
//     return this.buyerMasterRepository.updateAll(buyerMaster, where);
//   }
//   @get('/buyer-masters/{id}')
//   @response(200, {
//     description: 'BuyerMaster model instance',
//     content: {
//       'application/json': {
//         schema: getModelSchemaRef(BuyerMaster, {includeRelations: true}),
//       },
//     },
//   })
//   async findById(
//     @param.path.number('id') id: number,
//     @param.filter(BuyerMaster, {exclude: 'where'}) filter?: FilterExcludingWhere<BuyerMaster>
//   ): Promise<BuyerMaster> {
//     return this.buyerMasterRepository.findById(id, filter);
//   }
//   @patch('/buyer-masters/{id}')
//   @response(204, {
//     description: 'BuyerMaster PATCH success',
//   })
//   async updateById(
//     @param.path.number('id') id: number,
//     @requestBody({
//       content: {
//         'application/json': {
//           schema: getModelSchemaRef(BuyerMaster, {partial: true}),
//         },
//       },
//     })
//     buyerMaster: BuyerMaster,
//   ): Promise<void> {
//     await this.buyerMasterRepository.updateById(id, buyerMaster);
//   }
//   @put('/buyer-masters/{id}')
//   @response(204, {
//     description: 'BuyerMaster PUT success',
//   })
//   async replaceById(
//     @param.path.number('id') id: number,
//     @requestBody() buyerMaster: BuyerMaster,
//   ): Promise<void> {
//     await this.buyerMasterRepository.replaceById(id, buyerMaster);
//   }
//   @del('/buyer-masters/{id}')
//   @response(204, {
//     description: 'BuyerMaster DELETE success',
//   })
//   async deleteById(@param.path.number('id') id: number): Promise<void> {
//     await this.buyerMasterRepository.deleteById(id);
//   }
// }
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");
// ---------- Configure Upload Directory ----------
const uploadDir = path_1.default.join(__dirname, '../../uploads/buyer-profiles');
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 BuyermasterController = class BuyermasterController {
    constructor(buyerMasterRepository) {
        this.buyerMasterRepository = buyerMasterRepository;
    }
    async create(buyerMaster) {
        return this.buyerMasterRepository.create(buyerMaster);
    }
    // ---------- CREATE with file ----------
    async createWithFile(request, response) {
        return new Promise((resolve, reject) => {
            upload.single('profilePhoto')(request, response, async (err) => {
                if (err)
                    return reject(err);
                const file = request.file;
                const fields = request.body;
                try {
                    const newBuyer = await this.buyerMasterRepository.create({
                        buyerName: fields.buyerName,
                        buyerEmail: fields.buyerEmail,
                        buyerMobile: fields.buyerMobile,
                        fkcityId: fields.fkcityId,
                        buyerGender: fields.buyerGender,
                        fkusertypeId: fields.fkusertypeId,
                        profilePhoto: file ? `${constants_1.URL}/uploads/buyer-profiles/${file.filename}` : undefined,
                        isActive: 1,
                        lastChanged: new Date().toISOString(),
                    });
                    // Fetch with relations
                    const buyerWithRelations = await this.buyerMasterRepository.findById(newBuyer.buyerId, {
                        include: ['city', 'gender', 'usertype'],
                    });
                    resolve(buyerWithRelations);
                }
                catch (e) {
                    reject(e);
                }
            });
        });
    }
    // ---------- COUNT ----------
    async count(where) {
        return this.buyerMasterRepository.count(where);
    }
    // ---------- FIND ALL ----------
    async find(filter) {
        const f = {
            ...filter,
            include: ['city', 'gender', 'usertype'],
        };
        return this.buyerMasterRepository.find(f);
    }
    // ---------- FIND BY ID ----------
    async findById(id, filter) {
        const f = {
            ...filter,
            include: ['city', 'gender', 'usertype'],
        };
        return this.buyerMasterRepository.findById(id, f);
    }
    // ---------- UPDATE with file ----------
    async updateByIdWithFile(id, request, response) {
        return new Promise((resolve, reject) => {
            upload.single('profilePhoto')(request, response, async (err) => {
                if (err)
                    return reject(err);
                const file = request.file;
                const fields = request.body;
                try {
                    const existingBuyer = await this.buyerMasterRepository.findById(id);
                    await this.buyerMasterRepository.updateById(id, {
                        buyerName: fields.buyerName,
                        buyerEmail: fields.buyerEmail,
                        buyerMobile: fields.buyerMobile,
                        fkcityId: fields.fkcityId,
                        buyerGender: fields.buyerGender,
                        fkusertypeId: fields.fkusertypeId,
                        profilePhoto: file
                            ? `${constants_1.URL}/uploads/buyer-profiles/${file.filename}`
                            : existingBuyer.profilePhoto,
                        lastChanged: new Date().toISOString(),
                        isActive: fields.isActive,
                    });
                    // Return updated buyer with relations
                    const updatedBuyer = await this.buyerMasterRepository.findById(id, {
                        include: ['city', 'gender', 'usertype'],
                    });
                    resolve(updatedBuyer);
                }
                catch (e) {
                    reject(e);
                }
            });
        });
    }
    // ---------- DELETE ----------
    async deleteById(id) {
        await this.buyerMasterRepository.deleteById(id);
    }
    // ---------- SOFT DELETE ----------
    async softDelete(id) {
        await this.buyerMasterRepository.updateById(id, {
            isActive: 0,
            lastChanged: new Date().toISOString(),
        });
        const softDeletedBuyer = await this.buyerMasterRepository.findById(id, {
            include: ['city', 'gender', 'usertype'],
        });
        return softDeletedBuyer;
    }
};
exports.BuyermasterController = BuyermasterController;
tslib_1.__decorate([
    (0, rest_1.post)('/buyer-masters/text'),
    (0, rest_1.response)(200, {
        description: 'BuyerMaster model instance',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.BuyerMaster) } },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.BuyerMaster, {
                    title: 'NewBuyerMaster',
                    exclude: ['buyerId'],
                }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], BuyermasterController.prototype, "create", null);
tslib_1.__decorate([
    (0, rest_1.post)('/buyer-masters'),
    (0, rest_1.response)(200, {
        description: 'Create BuyerMaster with profile photo and relations',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.BuyerMaster) } },
    }),
    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)
], BuyermasterController.prototype, "createWithFile", null);
tslib_1.__decorate([
    (0, rest_1.get)('/buyer-masters/count'),
    (0, rest_1.response)(200, {
        description: 'BuyerMaster model count',
        content: { 'application/json': { schema: repository_1.CountSchema } },
    }),
    tslib_1.__param(0, rest_1.param.where(models_1.BuyerMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], BuyermasterController.prototype, "count", null);
tslib_1.__decorate([
    (0, rest_1.get)('/buyer-masters'),
    (0, rest_1.response)(200, {
        description: 'Array of BuyerMaster model instances with relations',
        content: {
            'application/json': {
                schema: {
                    type: 'array',
                    items: (0, rest_1.getModelSchemaRef)(models_1.BuyerMaster, { includeRelations: true }),
                },
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.filter(models_1.BuyerMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], BuyermasterController.prototype, "find", null);
tslib_1.__decorate([
    (0, rest_1.get)('/buyer-masters/{id}'),
    (0, rest_1.response)(200, {
        description: 'BuyerMaster model instance with relations',
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.BuyerMaster, { includeRelations: true }),
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.param.filter(models_1.BuyerMaster, { exclude: 'where' })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], BuyermasterController.prototype, "findById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/buyer-masters/{id}'),
    (0, rest_1.response)(204, { description: 'BuyerMaster 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)
], BuyermasterController.prototype, "updateByIdWithFile", null);
tslib_1.__decorate([
    (0, rest_1.del)('/buyer-masters/{id}'),
    (0, rest_1.response)(204, { description: 'BuyerMaster 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)
], BuyermasterController.prototype, "deleteById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/buyer-masters/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)
], BuyermasterController.prototype, "softDelete", null);
exports.BuyermasterController = BuyermasterController = tslib_1.__decorate([
    tslib_1.__param(0, (0, repository_1.repository)(repositories_1.BuyerMasterRepository)),
    tslib_1.__metadata("design:paramtypes", [repositories_1.BuyerMasterRepository])
], BuyermasterController);
//# sourceMappingURL=buyermaster.controller.js.map