import {
  Body,
  Controller,
  Get,
  Inject,
  InternalServerErrorException,
  Param,
  ParseIntPipe,
  Post,
  Put,
} from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { firstValueFrom } from 'rxjs';

@Controller('api/blacklist')
export class BlackListGatewayController {
  constructor(@Inject('AUTH_SERVICE') private client: ClientProxy) {}

  @Get()
  async getAll() {
    try {
      console.log('ok calling gateway!');
      return await firstValueFrom(
        this.client.send({ cmd: 'blacklist_get_all' }, {}),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Something went wrong');
    }
  }

  @Get(':id')
  async getById(@Param('id', ParseIntPipe) id: number) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'blacklist_get_by_id' }, { id }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Something went wrong');
    }
  }

  @Post()
  async addBlackList(@Body() body: any) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'blacklist_add' }, { body }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Something went wrong');
    }
  }

  @Put(':id')
  async updateBlackList(
    @Param('id', ParseIntPipe) id: number,
    @Body() body: any,
  ) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'blacklist_update' }, { id, body }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Something went wrong');
    }
  }
}
