const secretPatterns = [
  /ghs_[A-Za-z0-9_]+/g,
  /github_pat_[A-Za-z0-9_]+/g,
  /sk-[A-Za-z0-9_-]+/g,
  /(client_secret|auth_secret|api_key|token|password)=([^ \n\r]+)/gi,
];

export const createRedactor = (values: string[]) => {
  const secrets = values.filter((value) => value.length >= 3);
  return (input: string) => {
    let output = input;
    for (const secret of secrets) {
      output = output.split(secret).join('[redacted]');
    }
    for (const pattern of secretPatterns) {
      output = output.replace(pattern, '$1=[redacted]');
    }
    return output;
  };
};

export const truncate = (value: string, maxBytes: number) => {
  const buffer = Buffer.from(value);
  if (buffer.byteLength <= maxBytes) return value;
  return `${buffer.subarray(0, maxBytes).toString('utf8')}\n[truncated]`;
};
