import jwt, { type SignOptions } from 'jsonwebtoken';
import { randomBytes } from 'crypto';
import type { JWTPayload } from '@horux/shared';

export interface TokenConfig {
  secret: string;
  accessExpiresIn: string;
  refreshExpiresIn: string;
}

export function generateAccessToken(payload: Omit<JWTPayload, 'iat' | 'exp'>, config: TokenConfig): string {
  const options: SignOptions = {
    expiresIn: config.accessExpiresIn as SignOptions['expiresIn'],
    jwtid: randomBytes(8).toString('hex'),
  };
  return jwt.sign(payload, config.secret, options);
}

export function generateRefreshToken(payload: Omit<JWTPayload, 'iat' | 'exp'>, config: TokenConfig): string {
  const options: SignOptions = {
    expiresIn: config.refreshExpiresIn as SignOptions['expiresIn'],
    jwtid: randomBytes(8).toString('hex'),
  };
  return jwt.sign(payload, config.secret, options);
}

export function verifyToken(token: string, secret: string): JWTPayload {
  return jwt.verify(token, secret) as JWTPayload;
}

export function decodeToken(token: string): JWTPayload | null {
  try {
    return jwt.decode(token) as JWTPayload;
  } catch {
    return null;
  }
}
