import {
  Body,
  Controller,
  Get,
  Inject,
  InternalServerErrorException,
  Param,
  ParseIntPipe,
  Post,
  Req,
} from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { Request } from 'express';
import { firstValueFrom } from 'rxjs';

@Controller('api/customer-log')
export class customerLogGatewayController {
  constructor(@Inject('CUSTOMER_LOG_SERVICE') private client: ClientProxy) {}

  @Get()
  async getAllCustorLogs(@Req() req: Request) {
    try {
      console.log('expected is runnign ');
      const protocol = req.protocol;
      const host = req.headers.host;

      return await firstValueFrom(
        this.client.send({ cmd: 'customer_log_get_all' }, { protocol, host }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException(
        'Something went wrong when fetching logs!',
      );
    }
  }

  @Post()
  async addCustomerLogs(@Body() body: any) {
    try {
      const result = await firstValueFrom(
        this.client.send({ cmd: 'customer_log_add' }, { body }),
      );
      return result;
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException(err);
    }
  }

  @Get('/get-logs-by-customer-id/:idCustomer')
  async getLogsByCustomerId(
    @Param('idCustomer', ParseIntPipe) idCustomer: number,
  ) {
    try {
      const result = await firstValueFrom(
        this.client.send(
          { cmd: 'get_customer_log_by_customer_id' },
          { idCustomer },
        ),
      );
      return result;
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException(err);
    }
  }
}
