import { TWY_CDN_URL } from "astro:env/server";

import { api } from "./api";
import { ApiResult } from "./types/api";
import type { LatestBuildsResponse } from "./types/api/builds";

export type DownloadPlatform = "windows" | "linux" | "meta";

export type DownloadOption = {
	platform: DownloadPlatform;
	label: string;
	version: string;
	href: string;
	icon: string;
};

type DownloadPlatformConfig = {
	platform: DownloadPlatform;
	label: string;
	icon: string;
	versionKey: keyof LatestBuildsResponse;
};

export const downloadPlatforms: DownloadPlatformConfig[] = [
	{
		platform: "windows",
		label: "Windows",
		icon: "/img/platforms/platform-windows.png",
		versionKey: "latestWindowsVersion",
	},
	{
		platform: "linux",
		label: "Linux",
		icon: "/img/platforms/platform-linux.png",
		versionKey: "latestLinuxVersion",
	},
	{
		platform: "meta",
		label: "Meta Quest",
		icon: "/img/platforms/platform-oculus.png",
		versionKey: "latestMetaVersion",
	},
];

export const buildDownloadOptions = (
	latestVersions: LatestBuildsResponse,
): DownloadOption[] =>
	downloadPlatforms.map(({ platform, label, icon, versionKey }) => {
		const version = latestVersions[versionKey];

		return {
			platform,
			label,
			version,
			href: `${TWY_CDN_URL}/builds/${encodeURIComponent(version)}/${platform}.zip`,
			icon,
		};
	});

export const getLatestDownloads = async (): Promise<ApiResult<DownloadOption[]>> => {
	const latestVersions = await api.builds.v1.getLatestVersions();
	if (!latestVersions.success)
		return ApiResult.failure<DownloadOption[]>(latestVersions.error);

	return ApiResult.success(buildDownloadOptions(latestVersions.data));
};
