/**
 * GitHub tag discovery helper for TRUEREF-0014.
 *
 * Fetches the list of git tags for a GitHub repository, used to validate
 * that a requested tag exists before queuing an indexing job.
 */

export interface GitHubTag {
	name: string;
	commit: { sha: string };
}

export class GitHubApiError extends Error {
	constructor(public readonly status: number) {
		super(`GitHub API error: HTTP ${status}`);
		this.name = 'GitHubApiError';
	}
}

/**
 * List up to 100 tags for a GitHub repository.
 *
 * @param owner   GitHub owner/organisation name
 * @param repo    GitHub repository name
 * @param token   Optional personal access token for private repos / rate-limit relief
 */
export async function listGitHubTags(
	owner: string,
	repo: string,
	token?: string
): Promise<GitHubTag[]> {
	const headers: Record<string, string> = {
		Accept: 'application/vnd.github.v3+json',
		'User-Agent': 'TrueRef/1.0'
	};
	if (token) headers['Authorization'] = `Bearer ${token}`;

	const response = await fetch(
		`https://api.github.com/repos/${owner}/${repo}/tags?per_page=100`,
		{ headers }
	);

	if (!response.ok) throw new GitHubApiError(response.status);
	return response.json() as Promise<GitHubTag[]>;
}

/**
 * Check whether a specific tag name exists in the remote repository.
 * Returns the matching tag record, or `null` if absent.
 */
export async function findGitHubTag(
	owner: string,
	repo: string,
	tag: string,
	token?: string
): Promise<GitHubTag | null> {
	const tags = await listGitHubTags(owner, repo, token);
	return tags.find((t) => t.name === tag) ?? null;
}
