// import * as bcrypt from 'bcrypt';
import * as bcrypt from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../backend/users/users.service';
import { Injectable } from '@nestjs/common';

@Injectable()
export class AuthorizationService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(email: string, password: string) {
    const user = await this.usersService.findByEmail(email);

    // if (!user) return null;

    // const isMatch = await bcrypt.compare(password, user.password);
    // if (!isMatch) return null;

    return user;
  }

  async login(user: any) {
    const payload = { sub: user.id, email: user.email, role: 2 };

    return {
      access_token: this.jwtService.sign(payload),
    };
  }

  async register(data: any) {
    const hashed = await bcrypt.hash(data.password, 10);

    return this.usersService.create({
      ...data,
      password: hashed,
    });
  }
}