// import {
//   Count,
//   CountSchema,
//   Filter,
//   FilterExcludingWhere,
//   repository,
//   Where,
// } from '@loopback/repository';

// 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);
//   }
// }



import {
  Count,
  CountSchema,
  Filter,
  FilterExcludingWhere,
  repository,
  Where,
} from '@loopback/repository';

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});

function removeRelations(data: any, relations: string[]) {
  const copy = {...data};
  for (const rel of relations) {
    if (copy[rel]) delete copy[rel];
  }
  return copy;
}

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('/seller-masters')
  @response(200, {
    description: 'SellerMaster model instance',
    content: {'application/json': {schema: getModelSchemaRef(SellerMaster)}},
  })
  async create(
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(SellerMaster, {
            title: 'NewSellerMaster',
            exclude: ['sellerId'], // auto increment
          }),
        },
      },
    })
    sellerMaster: Omit<SellerMaster, 'sellerId'>,
  ): Promise<SellerMaster> {
    return this.sellerMasterRepository.create(sellerMaster);
  }



  // 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,
      include: ['city',
        // 'package',
         'user', 'gender'],
    });
  }

  // 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,
      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)
  @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;
    let safeBody: any = {};
    let file: Express.Multer.File | undefined;

    if (req.is('multipart/form-data')) {
      // Handle file upload
      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] : []);
        });
      });
      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)
  @patch('/seller-masters-new/{id}')
  @response(200, {
    description: 'SellerMaster PATCH success',
    content: {'application/json': {schema: getModelSchemaRef(SellerMaster)}},
  })
  async updateSellerMasterById(
    @param.path.number('id') id: number,
  ): Promise<SellerMaster> {
    const req = this.request as any;
    let safeBody: any = {};
    let file: Express.Multer.File | undefined;

    if (req.is('multipart/form-data')) {
      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] : []);
        });
      });
      file = uploaded[0];
      safeBody = req.body || {};
    } else {
      safeBody = req.body;
    }

    // Convert values properly
    for (const key of Object.keys(safeBody)) {
      let val: any = 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
  @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 multiple records (bulk update with JSON only)
  @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> {
    // Convert empty string → null
    const safeBody: any = {...sellerMaster};
    Object.keys(safeBody).forEach(k => {
      if (safeBody[k] === '') safeBody[k] = null;
    });

    return this.sellerMasterRepository.updateAll(safeBody, 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);
  }
}
