// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

import { bytesToUuid, uuidToBytes } from "./_common.ts";
import { concat } from "jsr:/@std/bytes@^1.0.0-rc.3/concat";
import { validate as validateCommon } from "./common.ts";

const UUID_RE =
  /^[0-9a-f]{8}-[0-9a-f]{4}-[5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

/**
 * Determines whether a string is a valid
 * {@link https://www.rfc-editor.org/rfc/rfc9562.html#section-5.5 | UUIDv5}.
 *
 * @param id UUID value.
 *
 * @returns `true` if the string is a valid UUIDv5, otherwise `false`.
 *
 * @example Usage
 * ```ts
 * import { validate } from "@std/uuid/v5";
 * import { assert, assertFalse } from "@std/assert";
 *
 * assert(validate("7af94e2b-4dd9-50f0-9c9a-8a48519bdef0"));
 * assertFalse(validate(crypto.randomUUID()));
 * ```
 */
export function validate(id: string): boolean {
  return UUID_RE.test(id);
}

/**
 * Generates a
 * {@link https://www.rfc-editor.org/rfc/rfc9562.html#section-5.5 | UUIDv5}.
 *
 * @param namespace The namespace to use, encoded as a UUID.
 * @param data The data to hash to calculate the SHA-1 digest for the UUID.
 *
 * @returns A UUIDv5 string.
 *
 * @throws {TypeError} If the namespace is not a valid UUID.
 *
 * @example Usage
 * ```ts
 * import { NAMESPACE_URL } from "@std/uuid/constants";
 * import { generate, validate } from "@std/uuid/v5";
 * import { assert } from "@std/assert";
 *
 * const data = new TextEncoder().encode("python.org");
 * const uuid = await generate(NAMESPACE_URL, data);
 *
 * assert(validate(uuid));
 * ```
 */
export async function generate(
  namespace: string,
  data: Uint8Array,
): Promise<string> {
  if (!validateCommon(namespace)) {
    throw new TypeError("Invalid namespace UUID");
  }

  const space = uuidToBytes(namespace);
  const toHash = concat([new Uint8Array(space), data]);
  const buffer = await crypto.subtle.digest("sha-1", toHash);
  const bytes = new Uint8Array(buffer);

  bytes[6] = (bytes[6]! & 0x0f) | 0x50;
  bytes[8] = (bytes[8]! & 0x3f) | 0x80;

  return bytesToUuid(bytes);
}

// denoCacheMetadata={"headers":{"content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","server":"cloudflare","date":"Tue, 28 Jul 2026 12:31:15 GMT","content-type":"text/typescript","cf-cache-status":"HIT","vary":"Origin","x-jsr-backend":"modules","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","cf-ray":"a223e657fb147db6-LAX","age":"112265","cache-control":"public, max-age=31536000, immutable","cross-origin-resource-policy":"cross-origin","etag":"\"43a2e8b4ad2e99f532e4a012c2ecb8a1\"","x-content-type-options":"nosniff","x-robots-tag":"noindex","accept-ranges":"bytes","access-control-expose-headers":"*","content-length":"2102","set-cookie":"__cf_bm=80HtJkjOTNVS9Hzqo4bdpftfi0U0UjOcO3dPt0G2co8-1785241875.2006884-1.0.1.1-OOH7c5VGdlEy.wQXjg6YqUTZVXnIvWNP3vr6Qh6ARerfYKLhDxyfI4b0MdK6g0fEwY2fX5S7kPnv_xDFzNIkBDYlviT0zT3SAJ0fG5qosLgFquoZn7_TQhEhVmDNRa4J; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","access-control-allow-origin":"*","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=A6WC3j5ldkRC541iBdPzWph2io28ScYjNoKgPZeVDMgspnkHmFCUwFWVHxbc9t073i%2F6H59NbDPH4157%2BJw48N2gSiWFByDTFq%2FA6YYOSf8Bfy2USolThdo%3D\"}]}","alt-svc":"h3=\":443\"; ma=86400"},"url":"https://jsr.io/@std/uuid/0.224.3/v5.ts","time":1785241875}