import {
  Body,
  Controller,
  Get,
  Post,
  Put,
  Param,
  Inject,
  InternalServerErrorException,
} from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { firstValueFrom } from 'rxjs';

@Controller('/api/shop-item')
export class ShopItemGateway {
  constructor(@Inject('SHOP_SERVICE') private client: ClientProxy) {}

  @Post('/')
  async add(@Body() body: any) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'shop_item_add' }, { body }),
      );
    } catch (err) {
      throw new InternalServerErrorException('Add failed');
    }
  }

  @Get('/')
  async getAll() {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'shop_item_get_all' }, {}),
      );
    } catch (err) {
      throw new InternalServerErrorException('Get all failed');
    }
  }

  @Get('/:id')
  async getById(@Param('id') id: number) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'shop_item_get_by_id' }, id),
      );
    } catch (err) {
      throw new InternalServerErrorException('Get by ID failed');
    }
  }

  @Put(':id')
  async update(@Param('id') id: number, @Body() body: any) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'shop_item_update' }, { id, body }),
      );
    } catch (err) {
      throw new InternalServerErrorException('Update failed');
    }
  }

  @Get('/get-shop-item-by-merchant-id/:Merchant_idMerchant')
  async getShopItemByMerchantId(
    @Param('Merchant_idMerchant') Merchant_idMerchant: number,
  ) {
    try {
      return await firstValueFrom(
        this.client.send(
          { cmd: 'get_shop_item_by_merchant_id' },
          { Merchant_idMerchant },
        ),
      );
    } catch (err) {
      throw new InternalServerErrorException(
        'Error when fetching shop item by merchant id',
      );
    }
  }
}
