import {
  Body,
  Controller,
  Get,
  Inject,
  InternalServerErrorException,
  Param,
  ParseIntPipe,
  Post,
  Put,
  UseGuards,
  UsePipes,
  ValidationPipe,
} from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { ApiDefaultResponses } from 'apps/auth/src/common.utils';
import { UserRegistrationRequestDto } from 'apps/auth/src/dto/user-registration.req.dto';
import { User } from 'apps/auth/src/user/user.entity';
import { JwtAuthGuard } from 'libs/auth-core-lib/src/guards/jwt-auth-guard';
import { firstValueFrom } from 'rxjs';

@Controller('/api/user')
export class AuthUserGateway {
  constructor(@Inject('USER_SERVICE') private client: ClientProxy) {}

  @Post('/register')
  @ApiDefaultResponses('Registration completed!')
  @UsePipes(ValidationPipe)
  async doUserRegistration(@Body() user: any) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'user_register' }, { user }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('user registration failed!');
    }
  }

  @Get('/')
  @ApiDefaultResponses('User fetching completed!')
  async getAllUsers() {
    try {
      console.log('ok!2');
      return await firstValueFrom(
        this.client.send({ cmd: 'user_get_all' }, {}),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Failed to get users!');
    }
  }

  @Get('/:id')
  async getUserById(@Param('id', ParseIntPipe) id: number) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'user_get_by_id' }, { id }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Failed to get user by id!');
    }
  }

  @Put('/:id')
  @UsePipes(ValidationPipe)
  async updateUser(
    @Param('id', ParseIntPipe) id: number,
    @Body() userData: any,
  ) {
    try {
      console.log('ok');
      return await firstValueFrom(
        this.client.send({ cmd: 'user_update' }, { id, userData }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException('Failed to  update the user!');
    }
  }
}
