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-template')
export class SMSGateway {
  constructor(@Inject('SMS_TEMPLATE') private client: ClientProxy) {}

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

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

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

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