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

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

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

  @Get('/by-customer/:customerId')
  async getByCustomerId(@Param('customerId', ParseIntPipe) customerId: number) {
    try {
      return await firstValueFrom(
        this.client.send(
          { cmd: 'customer_savings_get_by_customer' },
          { customerId },
        ),
      );
    } catch (err) {
      console.error(err);
      throw new InternalServerErrorException(
        'Failed to fetch savings by customer ID',
      );
    }
  }

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

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

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