import { BadRequestException, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { EncryptionService } from '../encryption/encryption.service';
import { JwtConstants } from 'src/constants/jwt.constants';
import { UserSigninResDto } from './dto/user-signin-res.dto';
import { User } from 'src/user/entities/user.entity';
import { UserService } from 'src/user/user.service';
import { CreateUserDto } from 'src/user/dto/create-user.dto';
import { LoginUserDto } from './dto/login-user.dto';

@Injectable()
export class AuthUserService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
    private encryptionService: EncryptionService,
  ) {}

  async signUp(createAdminDto: CreateUserDto): Promise<UserSigninResDto> {
    const loginAdminDto: LoginUserDto = {
      email: createAdminDto.email,
      password: createAdminDto.password,
    };
    const hashedPwd = await this.encryptionService.hashPassword(createAdminDto.password);
    createAdminDto.password = hashedPwd;
    if (await this.userService.userExists(createAdminDto.email)) {
      throw new BadRequestException('User already exists');
    }
    await this.userService.create(createAdminDto);

    const adminSigninResDto: UserSigninResDto = await this.signIn(loginAdminDto);
    return adminSigninResDto;
  }

  async signIn(logInAdmin: LoginUserDto): Promise<UserSigninResDto> {
    const user: User = await this.userService.findOne(logInAdmin.email);
    if (!user) throw new UnauthorizedException('Invalid credentials');
    const validPwd: boolean = await this.encryptionService.comparePassword(logInAdmin.password, user.password);
    if (!validPwd) {
      throw new UnauthorizedException('Invalid credentials');
    }
    const accessToken = await this.jwtService.sign(
      { email: user.email, name: user.name, lastName: user.lastName },
      { secret: JwtConstants.SECRET },
    );
    const userSigninResDto: UserSigninResDto = {
      userId: user.userId,
      email: user.email,
      name: user.name,
      lastName: user.lastName,
      token: accessToken,
    };
    return userSigninResDto;
  }
}
