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

@Controller('api/payment-methods')
export class PaymentMethodGatewayController {
  constructor(@Inject('CUSTOMER_SERVICE') private client: ClientProxy) {}

  @Get()
  async getAll() {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'payment_method_get_all' }, {}),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Failed to fetch payment methods');
    }
  }

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

  @Get('/get-by-customer/:id')
  async getByCustomerId(@Param('id', ParseIntPipe) id: number) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'payment_method_get_by_customer' }, { id }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException(
        'Failed to fetch customer methods',
      );
    }
  }

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

  @Put('/:id')
  async update(@Param('id', ParseIntPipe) id: number, @Body() body: any) {
    try {
      console.log('ok gateway handles');
      return await firstValueFrom(
        this.client.send({ cmd: 'payment_method_update' }, { id, ...body }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Failed to update payment method');
    }
  }
}
