import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class AuthService {
  constructor(private readonly jwtService: JwtService) {}

  generateTokens(payload: any) {
    const accessToken = this.jwtService.sign(payload, { expiresIn: '5s' });
    const refreshToken = this.jwtService.sign({id: payload.id}, { expiresIn: '7d' });

    return { accessToken, refreshToken };
  }

  refreshTokens(refreshToken: string) {
    try {
      const payload = this.jwtService.verify(refreshToken);
      return this.generateTokens(payload);
    } catch (e) {
      throw new UnauthorizedException('Invalid Refresh Token');
    }
  }
}