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-log')
export class BlackListLogGatewayController {
  constructor(@Inject('AUTH_SERVICE') private client: ClientProxy) {}

  @Get()
  async getAllLogs() {
    try {
      console.log('Fetching all blacklist logs from gateway');
      return await firstValueFrom(
        this.client.send({ cmd: 'blacklist_log_get_all' }, {}),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Failed to fetch blacklist logs');
    }
  }

  @Get(':id')
  async getLogById(@Param('id', ParseIntPipe) id: number) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'blacklist_log_get_by_id' }, { id }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Failed to fetch blacklist log');
    }
  }

  @Post()
  async addLog(@Body() body: any) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'blacklist_log_add' }, { body }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Failed to add blacklist log');
    }
  }

  @Put(':id')
  async updateLog(@Param('id', ParseIntPipe) id: number, @Body() body: any) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'blacklist_log_update' }, { id, body }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Failed to update blacklist log');
    }
  }
}
