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-category')
export class ShopItemCategoryGateway {
  constructor(@Inject('SHOP_SERVICE') private client: ClientProxy) {}

  @Post('/')
  async add(@Body() body: any) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'shop_item_category_add' }, { body }),
      );
    } catch (err) {
      throw new InternalServerErrorException('Add failed');
    }
  }

  @Get('/')
  async getAll() {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'shop_item_category_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_category_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_category_update' }, { id, body }),
      );
    } catch (err) {
      throw new InternalServerErrorException('Update failed');
    }
  }

  @Get('/by-merchant/:Merchant_idMerchant')
  async getByMerchantId(
    @Param('Merchant_idMerchant') Merchant_idMerchant: number,
  ) {
    try {
      return await firstValueFrom(
        this.client.send(
          { cmd: 'shop_item_category_get_by_merchant_id' },
          { Merchant_idMerchant },
        ),
      );
    } catch (err) {
      throw new InternalServerErrorException(
        'Error fetching categories by merchant ID',
      );
    }
  }
}
