import {
  Controller,
  Get,
  Post,
  Put,
  Body,
  Param,
  ParseIntPipe,
  Inject,
  UploadedFiles,
  UseInterceptors,
  Req,
} from '@nestjs/common';
import * as fs from 'fs';
import { Request } from 'express';
import { ClientProxy } from '@nestjs/microservices';
import { FileFieldsInterceptor } from '@nestjs/platform-express';
import { extname, join } from 'path';
import { diskStorage } from 'multer';

@Controller('api/merchant')
export class MerchantGatewayController {
  constructor(@Inject('MERCHANT_SERVICE') private client: ClientProxy) {}

  @Get()
  getAllMerchants(@Req() req: Request) {
    const protocol = req.protocol;
    const host = req.headers.host;

    return this.client.send({ cmd: 'merchant_get_all' }, { protocol, host });
  }

  @Get(':id')
  getMerchantById(@Param('id', ParseIntPipe) id: number, @Req() req: Request) {
    const protocol = req.protocol;
    const host = req.headers.host;
    return this.client.send(
      { cmd: 'merchant_get_by_id' },
      { id, protocol, host },
    );
  }

  @Post()
  @UseInterceptors(
    FileFieldsInterceptor(
      [
        { name: 'Logo', maxCount: 1 },
        { name: 'documents', maxCount: 10 },
      ],
      {
        storage: diskStorage({
          destination: (req, file, cb) => {
            const folder =
              file.fieldname === 'Logo' ? 'merchant' : 'merchant/documents';
            const folderPath = join(
              __dirname,
              '..',
              '..',
              '..',
              'uploads',
              folder,
            );

            // Ensure the directory exists, if not, create it
            if (!fs.existsSync(folderPath)) {
              fs.mkdirSync(folderPath, { recursive: true });
            }

            cb(null, folderPath);
          },
          filename: (req, file, cb) => {
            const uniqueSuffix =
              Date.now() + '-' + Math.round(Math.random() * 1e9);
            cb(null, `${uniqueSuffix}${extname(file.originalname)}`);
          },
        }),
      },
    ),
  )
  createMerchant(
    @Body() body: any,
    @UploadedFiles()
    files: { Logo?: Express.Multer.File[]; documents?: Express.Multer.File[] },
  ) {
    console.log('add method here is calling!');
    const merchantCategory = body.merchantCategory;
    console.log('Merchant category in gateway : ', merchantCategory);
    return this.client.send(
      { cmd: 'merchant_create' },
      { body, files, merchantCategory },
    );
  }

  @Put(':id')
  @UseInterceptors(
    FileFieldsInterceptor(
      [
        { name: 'Logo', maxCount: 1 },
        { name: 'documents', maxCount: 10 },
      ],
      {
        storage: diskStorage({
          destination: (req, file, cb) => {
            const folder =
              file.fieldname === 'Logo' ? 'merchant' : 'merchant/documents';
            const folderPath = join(
              __dirname,
              '..',
              '..',
              '..',
              'uploads',
              folder,
            );
            if (!fs.existsSync(folderPath)) {
              fs.mkdirSync(folderPath, { recursive: true });
            }
            cb(null, folderPath);
          },
          filename: (req, file, cb) => {
            const uniqueSuffix =
              Date.now() + '-' + Math.round(Math.random() * 1e9);
            cb(null, `${uniqueSuffix}${extname(file.originalname)}`);
          },
        }),
      },
    ),
  )
  updateMerchant(
    @Param('id', ParseIntPipe) id: number,
    @Body() body: any,
    @UploadedFiles()
    files: { Logo?: Express.Multer.File[]; documents?: Express.Multer.File[] },
  ) {
    console.log('In here we are calling update operation ');
    const merchantCategory = body.merchantCategoryNew;
    return this.client.send(
      { cmd: 'merchant_update' },
      { id, body, files, merchantCategory },
    );
  }
}
