/*
https://docs.nestjs.com/providers#services
*/

import {
  BadRequestException,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { UserService } from '../user/user.service';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { UserRegistrationRequestDto } from '../dto/user-registration.req.dto';
import { MechantRegistrationRequestDto } from '../dto/mechant-registration.req.dto';
import { MerchantuserService } from '../merchantuser/merchantuser.service';
import { RpcException } from '@nestjs/microservices';
@Injectable()
export class AuthService {
  constructor(
    private userDbService: UserService,
    private merchandtDbService: MerchantuserService,
    private jwtService: JwtService,
  ) {}

  async validateUserCredintials(Email: string, Password: string) {
    const user = await this.userDbService.getUserByEmail(Email);
    if (!user) {
      throw new RpcException({
        message: 'Email is not registered',
        statusCode: 404,
      });
    }

    const trimmedPassword = Password.trim();
    console.log('Trimmed password : ', trimmedPassword);
    const isPasswordValid = await bcrypt.compare(
      trimmedPassword,
      user.Password,
    );
    console.log(isPasswordValid);

    if (!isPasswordValid)
      throw new RpcException('Email or Password is incorrect');
    return user;
  }

  async genarateToken(user: any, type: string): Promise<any> {
    let access_token;
    if (type == 'user') {
      access_token = this.jwtService.sign({
        Name: user.Name,
        sub: user.idUser,
      });
    } else if (type == 'merchant_user') {
      access_token = this.jwtService.sign({
        Name: user.Full_Name,
        sub: user.idMarchant_User,
      });
    }

    return { access_token: access_token };
  }

  async registerUser(userData: any): Promise<any> {
    const newUser = await this.userDbService.doUserRegistration(userData);
    const token = await this.genarateToken(newUser, 'user');

    return {
      message: 'User registered successfully',
      user: newUser,
      token,
    };
  }

  async registerMarchantUser(
    userData: MechantRegistrationRequestDto,
  ): Promise<any> {
    const newMarchant =
      await this.merchandtDbService.doMerchantUserRegistration(userData);
    const token = await this.genarateToken(newMarchant, 'merchant_user');
    return {
      message: 'Merchant Registration completed!',
      merchandtUser: newMarchant,
      token,
    };
  }
}
