import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { AppConfig } from '@/config/configs';
import bcrypt from 'bcryptjs';

@Injectable()
export class AuthHelper {
  constructor(
    private readonly configService: ConfigService<AppConfig, true>,
    private readonly jwtService: JwtService,
  ) {}

  async hashPassword(password: string): Promise<string> {
    return bcrypt.hash(password, 10);
  }

  async verifyPassword(password: string, hash: string): Promise<boolean> {
    return bcrypt.compare(password, hash);
  }

  generateToken(payload: any): string {
    const secret = this.configService.get('auth.jwtSecret', { infer: true });
    const expiresIn = this.configService.get('auth.jwtExpiresIn', { infer: true });
    return this.jwtService.sign(payload, {
      secret,
      expiresIn: expiresIn as any,
    });
  }

  verifyToken(token: string): any {
    try {
      const secret = this.configService.get('auth.jwtSecret', { infer: true });
      return this.jwtService.verify(token, { secret });
    } catch (error) {
      return null;
    }
  }
}
