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

@Controller('api/customer-saving-log')
export class CustomerSavingLogGatewayController {
  constructor(@Inject('CUSTOMER_SERVICE') private client: ClientProxy) {}

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

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

  @Get('/by-saving/:id')
  async getBySavingId(@Param('id', ParseIntPipe) id: number) {
    try {
      return await firstValueFrom(
        this.client.send(
          { cmd: 'customer_saving_log_get_by_saving_id' },
          { id },
        ),
      );
    } catch (err) {
      console.error(err);
      throw new InternalServerErrorException(
        'Failed to fetch log by saving ID',
      );
    }
  }

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