import { randomBytes, createHash } from 'node:crypto';

const PREFIX = 'dfl_';

export function generateToken() {
  return PREFIX + randomBytes(32).toString('hex');
}

export function hashToken(token) {
  return createHash('sha256').update(token).digest('hex');
}

export function parseBearer(authorizationHeader) {
  if (!authorizationHeader || typeof authorizationHeader !== 'string') return null;
  const m = authorizationHeader.match(/^Bearer\s+(\S+)$/i);
  return m ? m[1] : null;
}

export const TOKEN_PREFIX_DISPLAY_LEN = 8; // for api_tokens.token_prefix
export function tokenDisplayPrefix(token) {
  return token.slice(0, TOKEN_PREFIX_DISPLAY_LEN);
}
