import {
  Controller,
  Post,
  Get,
  Put,
  Param,
  UploadedFile,
  UseInterceptors,
  Body,
  Inject,
  InternalServerErrorException,
  Req,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ClientProxy } from '@nestjs/microservices';
import { firstValueFrom } from 'rxjs';
import { diskStorage } from 'multer';
import { extname } from 'path';
import { Request } from 'express';
@Controller('/api/shop-item-sub-category')
export class ShopItemSubCategoryGateway {
  constructor(@Inject('SHOP_SERVICE') private client: ClientProxy) {}

  @Post('/')
  @UseInterceptors(
    FileInterceptor('Icon_Path', {
      storage: diskStorage({
        destination: './uploads/shop/sub-category-icons',
        filename: (req, file, cb) => {
          const uniqueName = `${Date.now()}${extname(file.originalname)}`;
          cb(null, uniqueName);
        },
      }),
    }),
  )
  async add(@UploadedFile() file: Express.Multer.File, @Body() body: any) {
    try {
      body.Icon_Path = file?.filename ?? null;
      return await firstValueFrom(
        this.client.send({ cmd: 'shop_item_sub_category_add' }, { body }),
      );
    } catch (err) {
      throw new InternalServerErrorException('Add failed');
    }
  }

  @Get('/')
  async getAll(@Req() req: Request) {
    try {
      const protocol = req.protocol;
      const host = req.headers.host;
      return await firstValueFrom(
        this.client.send(
          { cmd: 'shop_item_sub_category_get_all' },
          { protocol, host },
        ),
      );
    } catch (err) {
      throw new InternalServerErrorException('Get all failed');
    }
  }

  @Get('/:id')
  async getById(@Param('id') id: number, @Req() req: Request) {
    try {
      const protocol = req.protocol;
      const host = req.headers.host;
      return await firstValueFrom(
        this.client.send(
          { cmd: 'shop_item_sub_category_get_by_id' },
          { id, protocol, host },
        ),
      );
    } catch (err) {
      throw new InternalServerErrorException('Get by ID failed');
    }
  }

  @Put('/:id')
  @UseInterceptors(
    FileInterceptor('Icon_Path', {
      storage: diskStorage({
        destination: './uploads/sub-category-icons',
        filename: (req, file, cb) => {
          const uniqueName = `${Date.now()}${extname(file.originalname)}`;
          cb(null, uniqueName);
        },
      }),
    }),
  )
  async update(
    @Param('id') id: number,
    @UploadedFile() file: Express.Multer.File,
    @Body() body: any,
  ) {
    try {
      if (file) {
        body.Icon_Path = file.filename;
      }
      return await firstValueFrom(
        this.client.send(
          { cmd: 'shop_item_sub_category_update' },
          { id, body },
        ),
      );
    } catch (err) {
      throw new InternalServerErrorException('Update failed');
    }
  }
}
