import { Type } from "@sinclair/typebox";
import { FirRouteInput, FirRouteOptions } from "../util/routewrap";
import {git} from "../util/git.ts";
import { randomUUID } from "crypto";
import path from "path";
import {fileURLToPath} from 'url';
import { getCarts } from "../util/carts.ts";
const __dirname = fileURLToPath(new URL('.', import.meta.url));
const reposPath = path.resolve(__dirname, "..", "..", "..", "repos");

const method = "POST";
const url = "/api/release";

const payloadT = Type.Any();

const handler = async ({payload}: FirRouteInput<typeof payloadT>) => {
	const {manifest, token} = payload;

	const uuid = randomUUID();
	const repoPath = path.join(reposPath, uuid);

	await git.clone({
		from: manifest.repo,
		to: repoPath,
		auth: token,
	});

	const carts = await getCarts(manifest.carts.map((name: string) => path.join(repoPath, name)));

	console.log({
		manifest,
		carts,
	});

	return true;
};

export default {
	method,
	url,
	payloadT,
	handler,
} as const satisfies FirRouteOptions<typeof payloadT>;