import { Injectable } from '@nestjs/common';
import * as jwt from 'jsonwebtoken';

@Injectable()
export class AuthService {
  private readonly jwtSecret: jwt.Secret = process.env.JWT_SECRET || 'default_secret';

  sign(payload: Record<string, any>, expiresIn = '1d'): string {
    return jwt.sign(payload, this.jwtSecret, { expiresIn } as jwt.SignOptions);
  }

  verify(token: string): Record<string, any> | null {
    try {
      const decoded = jwt.verify(token, this.jwtSecret) as jwt.JwtPayload | string;
      return typeof decoded === 'string' ? { sub: decoded } : (decoded as Record<string, any>);
    } catch {
      return null;
    }
  }
}
