/*
https://docs.nestjs.com/controllers#controllers
*/

import { Controller, Post, UseGuards, Request, Body } from '@nestjs/common';
import { AuthService } from './auth.service';
import { LocalAuthGuard } from '../../../../libs/auth-core-lib/src/guards/local-auth.guard';

import { ApiDefaultResponses } from '../common.utils';
import { UserRegistrationRequestDto } from '../dto/user-registration.req.dto';
import { MechantRegistrationRequestDto } from '../dto/mechant-registration.req.dto';
import { MessagePattern, RpcException } from '@nestjs/microservices';
@Controller()
export class AuthController {
  constructor(private authDbService: AuthService) {}

  @MessagePattern({ cmd: 'LOGIN_USER' })
  async login(data: { user }): Promise<any> {
    try {
      const { user } = data;
      console.log('user ', user);

      if (!user) {
        console.log('user not coming!');
        throw new RpcException({
          statusCode: 401,
          message: 'Invalid credentials',
        });
      }
      const token = await this.authDbService.genarateToken(user, 'user');
      return {
        message: 'Login success!',
        user: user,
        token: token,
      };
    } catch (err) {
      console.log(err);

      throw new RpcException('User fetching failed!');
    }
  }

  @MessagePattern({ cmd: 'AUTH_REGISTER' })
  async register(data: { body: any }): Promise<any> {
    try {
      const { body } = data;
      return this.authDbService.registerUser(body);
    } catch (err) {
      console.error(err);
      throw new RpcException('Registration Issue');
    }
  }

  @MessagePattern({ cmd: 'REGISTER_MERCHANT_USER' })
  async registerMerchant(data: { body: any }): Promise<any> {
    try {
      const { body } = data;
      return this.authDbService.registerMarchantUser(body);
    } catch (err) {
      console.error(err);
      throw new RpcException('Merchant Registration Failed!');
    }
  }

  @MessagePattern({ cmd: 'validate_user_credentials' })
  async validateUserCredentials(data: { Email: string; Password: string }) {
    const { Email, Password } = data;

    const user = await this.authDbService.validateUserCredintials(
      Email,
      Password,
    );

    if (!user) {
      return { user: null };
    }

    return { user };
  }
}
