import {
  Body,
  Controller,
  HttpException,
  Inject,
  InternalServerErrorException,
  Post,
  Request,
  UseGuards,
} from '@nestjs/common';
import { ClientProxy } from '@nestjs/microservices';
import { LocalAuthGuard } from 'libs/auth-core-lib/src/guards/local-auth.guard';
import { firstValueFrom } from 'rxjs';

@Controller('/api/authentication')
export class AuthenticationGateway {
  constructor(@Inject('AUTH_SERVICE') private client: ClientProxy) {}

  @UseGuards(LocalAuthGuard)
  @Post('/login')
  async login(@Request() req) {
    try {
      console.log('ok calling!', req.user); // only user data
      return await firstValueFrom(
        this.client.send({ cmd: 'LOGIN_USER' }, { user: req.user }),
      );
    } catch (err) {
      console.log(err);
      const errorResponse = err?.response || err?.message;

      if (typeof errorResponse === 'object' && errorResponse.statusCode) {
        throw new HttpException(
          errorResponse.message,
          errorResponse.statusCode,
        );
      }

      throw new InternalServerErrorException(
        'Something went wrong when login!',
      );
    }
  }

  @Post('/register')
  async register(@Body() body: any) {
    try {
      return await firstValueFrom(
        this.client.send({ cmd: 'AUTH_REGISTER' }, { body }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException(
        'Something went wrong when registering!',
      );
    }
  }

  @Post('/register-merchant-user')
  async registerMerchant(@Body() body: any) {
    try {
      console.log('ok here is calling@');
      return await firstValueFrom(
        this.client.send({ cmd: 'REGISTER_MERCHANT_USER' }, { body }),
      );
    } catch (err) {
      console.log(err);
      throw new InternalServerErrorException(
        'Something went wrong when registering the merchant!',
      );
    }
  }

  // @UseGuards(LocalAuthGuard)
  // @Post('/merchant-user-login')
  // async merchantUserLogin(@Request() req) {
  //   try {
  //     return await firstValueFrom(
  //       this.client.send({ cmd: 'MERCHANT_USER_LOGIN' }, { user: req.user }),
  //     );
  //   } catch (err) {
  //     console.log(err);
  //     throw new InternalServerErrorException(
  //       'Something went wrong when login the merchant!',
  //     );
  //   }
  // }
}
