#! /usr/bin/env deno run --allow-net --allow-env
import {Issue} from "./githubType.ts";
import {parse} from "https://deno.land/std@0.135.0/flags/mod.ts";
import "https://deno.land/std@0.136.0/dotenv/load.ts";

/**
 * get issue from github
 * @param repo repository name with owner (e.g. denoland/deno)
 * @param token your github token
 * @returns up to 100 issue objects
 * @example
 * ```ts
 * const issues = await getIssues('denoland/deno', 'your-token')
 * console.log(issues);
 * ```
 */
export async function getIssues(repo: string, token: string): Promise<Issue[]> {
    //check https://docs.github.com/en/rest/reference/issues#list-repository-issues
    const res = await fetch(`https://api.github.com/repos/${repo}/issues?per_page=100&labels=feature&state=all`, {
        headers: {
            Accept: 'application/vnd.github.v3+json',
            Authorization: `Token ${token}`
        }
    });
    return await res.json();
}


if (import.meta.main) {
    const args = parse(Deno.args);
    const token = args.token ?? Deno.env.get("GITHUB_TOKEN");
    if(typeof token !== "string"){
        console.error("invalid type: token must be string");
        Deno.exit(1);
    }
    if(!token) {
        console.error("GITHUB_TOKEN is not set");
        Deno.exit(1);
    }
    const issues = await getIssues("vi117/scrap-yard", token);
    issues.sort((a, b) => a.number - b.number);
    const content = JSON.stringify(issues, null, 2);
    if(typeof args.path === "string"){
        Deno.writeTextFileSync(args.path, content);
    }
    else{
        console.log(content);
    }
}