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

@Controller('api/default-credit-limit')
export class DefaultCreditLimitGateway {
  constructor(@Inject('AUTH_SERVICE') private client: ClientProxy) {}

  @Get()
  async getAll() {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'default_credit_limit_get_all' }, {}),
      );
    } catch (err) {
      console.error(err);
      throw new InternalServerErrorException('Failed to fetch credit limits');
    }
  }

  @Get(':id')
  async getById(@Param('id', ParseIntPipe) id: number) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'default_credit_limit_get_by_id' }, { id }),
      );
    } catch (err) {
      console.error(err);
      throw new InternalServerErrorException('Failed to fetch credit limit');
    }
  }

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

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