"use strict";
/* Socket Lib - Built with rolldown */
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
const require_primordials_json = require('../primordials/json.js');
const require_http_request_request = require('../http-request/request.js');
const require_github_constants = require('./constants.js');
const require_github_token = require('./token.js');

//#region src/github/refs-graphql.ts
/**
* @file Resolve a GitHub git ref via GraphQL. Split out of `github/refs.ts` for
*   size hygiene. The fallback the REST tier-cascade calls when it detects the
*   documented "200 + empty body" incident shape — GraphQL hits a different
*   backend at GitHub (not the same Elasticsearch index as REST listings) and
*   stays consistent through those incidents.
*/
/**
* Resolve a ref to its commit SHA via GraphQL.
*
* Why this function exists: This is the fallback that `fetchRefSha` calls when
* the REST tier-cascade detects the "GitHub returned 200 + empty body" incident
* shape. GraphQL hits a different backend than REST listings, so it stays
* consistent through the kinds of incidents that produce empty REST responses.
*
* What it does: The REST cascade needs three separate calls (tag, branch,
* commit) because REST has no single "resolve any ref" endpoint. GraphQL DOES —
* `Repository.ref(qualifiedName)` resolves tags AND branches by their
* fully-qualified name, and `Repository.object(oid)` resolves a raw commit SHA.
* We bundle all three into ONE query using GraphQL aliases (`tagRef`,
* `branchRef`, `commit`) and pick whichever resolved.
*
* Annotated vs lightweight tags: In Git, a "lightweight tag" is just a name
* that points directly at a commit. An "annotated tag" is a separate object
* (with tagger info, message, etc.) that itself points at the commit. GraphQL's
* `Tag.target` field gives us the commit SHA for annotated tags in one shot —
* REST needs a _second_ HTTP call to dereference. The `... on Tag { target {
* oid } }` / `... on Commit { oid }` inline-fragments handle both shapes.
*
* Return contract:
*
* - Returns the SHA string when any form matches.
* - Returns `undefined` when the ref genuinely doesn't exist as a tag, branch, OR
*   commit. The caller treats `undefined` the same as "REST cascade also
*   failed" — a real "ref not found".
* - Returns `undefined` (not throws) on transport-level failures too: non-OK
*   HTTP, empty GraphQL body, or JSON parse error. The REST cascade's "ref not
*   found" message is more useful to the end user than a GraphQL transport
*   error.
*/
async function fetchRefShaViaGraphQL(owner, repo, ref, options) {
	const token = options.token || require_github_token.getGitHubToken();
	const headers = {
		Accept: "application/vnd.github.v3+json",
		"Content-Type": "application/json",
		"User-Agent": "socket-registry-github-client",
		...options.headers
	};
	if (token) headers["Authorization"] = `Bearer ${token}`;
	const query = `query($owner: String!, $repo: String!, $tag: String!, $branch: String!, $oid: GitObjectID!) {
    repository(owner: $owner, name: $repo) {
      tagRef: ref(qualifiedName: $tag) {
        target {
          __typename
          ... on Tag { target { oid } }
          ... on Commit { oid }
        }
      }
      branchRef: ref(qualifiedName: $branch) {
        target { oid }
      }
      commit: object(oid: $oid) {
        __typename
        ... on Commit { oid }
      }
    }
  }`;
	const oidArg = /^[a-f0-9]{40}$/i.test(ref) ? ref : "0000000000000000000000000000000000000000";
	const response = await require_http_request_request.httpRequest(require_github_constants.GITHUB_GRAPHQL_URL, {
		body: require_primordials_json.JSONStringify({
			query,
			variables: {
				branch: `refs/heads/${ref}`,
				oid: oidArg,
				owner,
				repo,
				tag: `refs/tags/${ref}`
			}
		}),
		headers,
		method: "POST"
	});
	if (!response.ok || response.body.byteLength === 0) return;
	let parsed;
	try {
		parsed = require_primordials_json.JSONParse(response.body.toString("utf8"));
	} catch {
		return;
	}
	const repoData = parsed.data?.repository;
	/* c8 ignore start */
	if (!repoData) return;
	/* c8 ignore stop */
	const tagTarget = repoData.tagRef?.target;
	if (tagTarget) {
		/* c8 ignore start */
		if (tagTarget.__typename === "Tag") return tagTarget.target?.oid ?? void 0;
		if (tagTarget.__typename === "Commit") return tagTarget.oid ?? void 0;
	}
	const branchOid = repoData.branchRef?.target?.oid;
	if (branchOid) return branchOid;
	/* c8 ignore start */
	if (repoData.commit?.__typename === "Commit" && repoData.commit.oid) return repoData.commit.oid;
	/* c8 ignore stop */
}

//#endregion
exports.fetchRefShaViaGraphQL = fetchRefShaViaGraphQL;