"use strict";
// import {
//   Count,
//   CountSchema,
//   Filter,
//   FilterExcludingWhere,
//   repository,
//   Where,
// } from '@loopback/repository';
Object.defineProperty(exports, "__esModule", { value: true });
exports.SellermasterController = void 0;
const tslib_1 = require("tslib");
// import {
//   del,
//   get,
//   getModelSchemaRef,
//   param,
//   patch,
//   post,
//   put,
//   Request,
//   requestBody,
//   response,
//   RestBindings,
// } from '@loopback/rest';
// import {inject} from '@loopback/core';
// import fs from 'fs';
// import multer from 'multer';
// import path from 'path';
// import {SellerMaster} from '../models';
// import {SellerMasterRepository} from '../repositories';
// // Upload directory path
// const uploadDir = path.resolve(__dirname, '../../uploads/seller-profiles');
// fs.mkdirSync(uploadDir, {recursive: true});
// // Multer storage config
// const storage = multer.diskStorage({
//   destination(req, file, cb) {
//     cb(null, uploadDir);
//   },
//   filename(req, file, cb) {
//     const uniqueName = `${Date.now()}-${Math.round(Math.random() * 1e9)}${path.extname(file.originalname)}`;
//     cb(null, uniqueName);
//   },
// });
// const upload = multer({storage});
// export class SellermasterController {
//   constructor(
//     @inject(RestBindings.Http.REQUEST) private request: Request,
//     @repository(SellerMasterRepository)
//     public sellerMasterRepository: SellerMasterRepository,
//   ) { }
//   @post('/seller-masters-text')
//   @response(200, {
//     description: 'SellerMaster model instance',
//     content: {'application/json': {schema: getModelSchemaRef(SellerMaster)}},
//   })
//   async createJson(
//     @requestBody({
//       content: {
//         'application/json': {
//           schema: getModelSchemaRef(SellerMaster, {
//             title: 'NewSellerMaster',
//             exclude: ['sellerId'],
//           }),
//         },
//       },
//     })
//     sellerMaster: Omit<SellerMaster, 'sellerId'>,
//   ): Promise<SellerMaster> {
//     return this.sellerMasterRepository.create(sellerMaster);
//   }
//   // POST with file upload and form data
//   @post('/seller-masters')
//   @response(200, {
//     description: 'SellerMaster model instance',
//     content: {'application/json': {schema: getModelSchemaRef(SellerMaster)}},
//   })
//   async create(): Promise<SellerMaster> {
//     const req = this.request as any;
//     const uploaded = await new Promise<Express.Multer.File[]>((resolve, reject) => {
//       upload.single('sellerProfile')(req, {} as any, (err: any) => {
//         if (err) return reject(err);
//         resolve(req.file ? [req.file] : []);
//       });
//     });
//     const file = uploaded[0];
//     const body = req.body;
//     // Convert any string numeric fields if needed here before save
//     const newSeller = {
//       ...body,
//       sellerProfile: file ? file.filename : '',
//     };
//     return this.sellerMasterRepository.create(newSeller);
//   }
//   // GET count
//   @get('/seller-masters/count')
//   @response(200, {
//     description: 'SellerMaster model count',
//     content: {'application/json': {schema: CountSchema}},
//   })
//   async count(@param.where(SellerMaster) where?: Where<SellerMaster>): Promise<Count> {
//     return this.sellerMasterRepository.count(where);
//   }
//   // GET all
//   @get('/seller-masters')
//   @response(200, {
//     description: 'Array of SellerMaster model instances',
//     content: {
//       'application/json': {
//         schema: {
//           type: 'array',
//           items: getModelSchemaRef(SellerMaster, {includeRelations: true}),
//         },
//       },
//     },
//   })
//   async find(@param.filter(SellerMaster) filter?: Filter<SellerMaster>): Promise<SellerMaster[]> {
//     return this.sellerMasterRepository.find(filter);
//   }
//   // GET by id
//   @get('/seller-masters/{id}')
//   @response(200, {
//     description: 'SellerMaster model instance',
//     content: {
//       'application/json': {
//         schema: getModelSchemaRef(SellerMaster, {includeRelations: true}),
//       },
//     },
//   })
//   async findById(
//     @param.path.number('id') id: number,
//     @param.filter(SellerMaster, {exclude: 'where'}) filter?: FilterExcludingWhere<SellerMaster>,
//   ): Promise<SellerMaster> {
//     return this.sellerMasterRepository.findById(id, filter);
//   }
//   // PATCH by id with optional file upload
//   // PATCH by id with optional file upload
//   @patch('/seller-masters/{id}')
//   @response(204, {
//     description: 'SellerMaster PATCH success',
//   })
//   async updateById(@param.path.number('id') id: number): Promise<void> {
//     const req = this.request as any;
//     const uploaded = await new Promise<Express.Multer.File[]>(
//       (resolve, reject) => {
//         upload.single('sellerProfile')(req, {} as any, (err: any) => {
//           if (err) return reject(err);
//           resolve(req.file ? [req.file] : []);
//         });
//       },
//     );
//     const file = uploaded[0];
//     const body = req.body;
//     // 🛠️ Convert रिकामे values -> null (numeric fields साठी)
//     const safeBody: any = {...body};
//     if (safeBody.sellercompmobile === '' || safeBody.sellercompmobile === undefined) {
//       safeBody.sellercompmobile = null;
//     }
//     if (safeBody.sellercopmManegermob === '' || safeBody.sellercopmManegermob === undefined) {
//       safeBody.sellercopmManegermob = null;
//     }
//     const updatedSeller = {
//       ...safeBody,
//       ...(file ? {sellerProfile: file.filename} : {}),
//     };
//     await this.sellerMasterRepository.updateById(id, updatedSeller);
//   }
//   // PUT by id (replace) with optional file upload
//   @put('/seller-masters/{id}')
//   @response(204, {
//     description: 'SellerMaster PUT success',
//   })
//   async replaceById(@param.path.number('id') id: number): Promise<void> {
//     const req = this.request as any;
//     const uploaded = await new Promise<Express.Multer.File[]>((resolve, reject) => {
//       upload.single('sellerProfile')(req, {} as any, (err: any) => {
//         if (err) return reject(err);
//         resolve(req.file ? [req.file] : []);
//       });
//     });
//     const file = uploaded[0];
//     const body = req.body;
//     const replacedSeller = {
//       ...body,
//       sellerProfile: file ? file.filename : '',
//     };
//     await this.sellerMasterRepository.replaceById(id, replacedSeller);
//   }
//   // PATCH multiple records
//   @patch('/seller-masters')
//   @response(200, {
//     description: 'SellerMaster PATCH success count',
//     content: {'application/json': {schema: CountSchema}},
//   })
//   async updateAll(
//     @requestBody({
//       content: {
//         'application/json': {
//           schema: getModelSchemaRef(SellerMaster, {partial: true}),
//         },
//       },
//     })
//     sellerMaster: SellerMaster,
//     @param.where(SellerMaster) where?: Where<SellerMaster>,
//   ): Promise<Count> {
//     return this.sellerMasterRepository.updateAll(sellerMaster, where);
//   }
//   // DELETE by id
//   @del('/seller-masters/{id}')
//   @response(204, {
//     description: 'SellerMaster DELETE success',
//   })
//   async deleteById(@param.path.number('id') id: number): Promise<void> {
//     await this.sellerMasterRepository.deleteById(id);
//   }
// }
const repository_1 = require("@loopback/repository");
const rest_1 = require("@loopback/rest");
const core_1 = require("@loopback/core");
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 models_1 = require("../models");
const repositories_1 = require("../repositories");
// Upload directory path
const uploadDir = path_1.default.resolve(__dirname, '../../uploads/seller-profiles');
fs_1.default.mkdirSync(uploadDir, { recursive: true });
// Multer storage config
const storage = multer_1.default.diskStorage({
    destination(req, file, cb) {
        cb(null, uploadDir);
    },
    filename(req, file, cb) {
        const uniqueName = `${Date.now()}-${Math.round(Math.random() * 1e9)}${path_1.default.extname(file.originalname)}`;
        cb(null, uniqueName);
    },
});
const upload = (0, multer_1.default)({ storage });
function removeRelations(data, relations) {
    const copy = { ...data };
    for (const rel of relations) {
        if (copy[rel])
            delete copy[rel];
    }
    return copy;
}
let SellermasterController = class SellermasterController {
    constructor(request, sellerMasterRepository) {
        this.request = request;
        this.sellerMasterRepository = sellerMasterRepository;
    }
    async createJson(sellerMaster) {
        return this.sellerMasterRepository.create(sellerMaster);
    }
    async create(sellerMaster) {
        return this.sellerMasterRepository.create(sellerMaster);
    }
    // GET count
    async count(where) {
        return this.sellerMasterRepository.count(where);
    }
    // GET all
    async find(filter) {
        return this.sellerMasterRepository.find({
            ...filter,
            include: ['city',
                // 'package',
                'user', 'gender'],
        });
    }
    // GET by id
    async findById(id, filter) {
        return this.sellerMasterRepository.findById(id, {
            ...filter,
            include: [
                // {relation: 'package'},
                { relation: 'user' }, { relation: 'gender' }, { relation: 'city' }
            ],
        });
    }
    // PATCH by id with optional file upload
    // PATCH by id with optional file upload
    // PATCH by id (simple update with optional file upload)
    async updateById(id) {
        const req = this.request;
        let safeBody = {};
        let file;
        if (req.is('multipart/form-data')) {
            // Handle file upload
            const uploaded = await new Promise((resolve, reject) => {
                upload.single('sellerProfile')(req, {}, (err) => {
                    if (err)
                        return reject(err);
                    resolve(req.file ? [req.file] : []);
                });
            });
            file = uploaded[0];
            safeBody = req.body || {};
        }
        else {
            // JSON request
            safeBody = req.body;
        }
        // Convert empty strings to null
        Object.keys(safeBody).forEach(k => {
            if (safeBody[k] === '')
                safeBody[k] = null;
        });
        if (file)
            safeBody.sellerProfile = file.filename;
        // remove relation keys
        const allowedBody = removeRelations(safeBody, ['city',
            // 'package',
            'user', 'gender']);
        await this.sellerMasterRepository.updateById(id, allowedBody);
    }
    // PATCH by id (return updated Seller with relations, supports multipart + JSON)
    async updateSellerMasterById(id) {
        const req = this.request;
        let safeBody = {};
        let file;
        if (req.is('multipart/form-data')) {
            const uploaded = await new Promise((resolve, reject) => {
                upload.single('sellerProfile')(req, {}, (err) => {
                    if (err)
                        return reject(err);
                    resolve(req.file ? [req.file] : []);
                });
            });
            file = uploaded[0];
            safeBody = req.body || {};
        }
        else {
            safeBody = req.body;
        }
        // Convert values properly
        for (const key of Object.keys(safeBody)) {
            let val = safeBody[key];
            if (!isNaN(val) && val !== '')
                val = Number(val); // numbers
            if (val === 'true')
                val = true; // booleans
            if (val === 'false')
                val = false;
            if (val === '' || val === undefined)
                val = null; // empty → null
            safeBody[key] = val;
        }
        if (file)
            safeBody.sellerProfile = file.filename;
        await this.sellerMasterRepository.updateById(id, safeBody);
        return this.sellerMasterRepository.findById(id, {
            include: ['city',
                //  'package',
                'user', 'gender'],
        });
    }
    // PUT by id (replace) with optional file upload
    async replaceById(id) {
        const req = this.request;
        const uploaded = await new Promise((resolve, reject) => {
            upload.single('sellerProfile')(req, {}, (err) => {
                if (err)
                    return reject(err);
                resolve(req.file ? [req.file] : []);
            });
        });
        const file = uploaded[0];
        const body = req.body;
        const replacedSeller = {
            ...body,
            sellerProfile: file ? file.filename : '',
        };
        await this.sellerMasterRepository.replaceById(id, replacedSeller);
    }
    // PATCH multiple records
    // PATCH multiple records (bulk update with JSON only)
    async updateAll(sellerMaster, where) {
        // Convert empty string → null
        const safeBody = { ...sellerMaster };
        Object.keys(safeBody).forEach(k => {
            if (safeBody[k] === '')
                safeBody[k] = null;
        });
        return this.sellerMasterRepository.updateAll(safeBody, where);
    }
    // DELETE by id
    async deleteById(id) {
        await this.sellerMasterRepository.deleteById(id);
    }
};
exports.SellermasterController = SellermasterController;
tslib_1.__decorate([
    (0, rest_1.post)('/seller-masters-text'),
    (0, rest_1.response)(200, {
        description: 'SellerMaster model instance',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.SellerMaster) } },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.SellerMaster, {
                    title: 'NewSellerMaster',
                    exclude: ['sellerId'],
                }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], SellermasterController.prototype, "createJson", null);
tslib_1.__decorate([
    (0, rest_1.post)('/seller-masters'),
    (0, rest_1.response)(200, {
        description: 'SellerMaster model instance',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.SellerMaster) } },
    }),
    tslib_1.__param(0, (0, rest_1.requestBody)({
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.SellerMaster, {
                    title: 'NewSellerMaster',
                    exclude: ['sellerId'], // auto increment
                }),
            },
        },
    })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], SellermasterController.prototype, "create", null);
tslib_1.__decorate([
    (0, rest_1.get)('/seller-masters/count'),
    (0, rest_1.response)(200, {
        description: 'SellerMaster model count',
        content: { 'application/json': { schema: repository_1.CountSchema } },
    }),
    tslib_1.__param(0, rest_1.param.where(models_1.SellerMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], SellermasterController.prototype, "count", null);
tslib_1.__decorate([
    (0, rest_1.get)('/seller-masters'),
    (0, rest_1.response)(200, {
        description: 'Array of SellerMaster model instances',
        content: {
            'application/json': {
                schema: {
                    type: 'array',
                    items: (0, rest_1.getModelSchemaRef)(models_1.SellerMaster, { includeRelations: true }),
                },
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.filter(models_1.SellerMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Object]),
    tslib_1.__metadata("design:returntype", Promise)
], SellermasterController.prototype, "find", null);
tslib_1.__decorate([
    (0, rest_1.get)('/seller-masters/{id}'),
    (0, rest_1.response)(200, {
        description: 'SellerMaster model instance',
        content: {
            'application/json': {
                schema: (0, rest_1.getModelSchemaRef)(models_1.SellerMaster, { includeRelations: true }),
            },
        },
    }),
    tslib_1.__param(0, rest_1.param.path.number('id')),
    tslib_1.__param(1, rest_1.param.filter(models_1.SellerMaster, { exclude: 'where' })),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [Number, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], SellermasterController.prototype, "findById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/seller-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'SellerMaster PATCH 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)
], SellermasterController.prototype, "updateById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/seller-masters-new/{id}'),
    (0, rest_1.response)(200, {
        description: 'SellerMaster PATCH success',
        content: { 'application/json': { schema: (0, rest_1.getModelSchemaRef)(models_1.SellerMaster) } },
    }),
    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)
], SellermasterController.prototype, "updateSellerMasterById", null);
tslib_1.__decorate([
    (0, rest_1.put)('/seller-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'SellerMaster PUT 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)
], SellermasterController.prototype, "replaceById", null);
tslib_1.__decorate([
    (0, rest_1.patch)('/seller-masters'),
    (0, rest_1.response)(200, {
        description: 'SellerMaster 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.SellerMaster, { partial: true }),
            },
        },
    })),
    tslib_1.__param(1, rest_1.param.where(models_1.SellerMaster)),
    tslib_1.__metadata("design:type", Function),
    tslib_1.__metadata("design:paramtypes", [models_1.SellerMaster, Object]),
    tslib_1.__metadata("design:returntype", Promise)
], SellermasterController.prototype, "updateAll", null);
tslib_1.__decorate([
    (0, rest_1.del)('/seller-masters/{id}'),
    (0, rest_1.response)(204, {
        description: 'SellerMaster 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)
], SellermasterController.prototype, "deleteById", null);
exports.SellermasterController = SellermasterController = tslib_1.__decorate([
    tslib_1.__param(0, (0, core_1.inject)(rest_1.RestBindings.Http.REQUEST)),
    tslib_1.__param(1, (0, repository_1.repository)(repositories_1.SellerMasterRepository)),
    tslib_1.__metadata("design:paramtypes", [Object, repositories_1.SellerMasterRepository])
], SellermasterController);
//# sourceMappingURL=sellermaster.controller.js.map