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

@Controller('/api/sms-history')
export class SMSHistoryGateway {
  constructor(@Inject('SMS_TEMPLATE') private client: ClientProxy) {}

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

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

  @Get('/:id')
  async getByid(@Param('id', ParseIntPipe) id: number) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'sms_history_get_by_id' }, { id }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Failed to add history!');
    }
  }

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

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