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

import { api } from "$lib/api";

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

import windowsIcon from "$assets/images/platforms/platform-windows.png";
import linuxIcon from "$assets/images/platforms/platform-linux.png";
import metaIcon from "$assets/images/platforms/platform-oculus.png";

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

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

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

export const downloadPlatforms: DownloadPlatformConfig[] = [
	{
		platform: "windows",
		label: "Windows",
		icon: windowsIcon,
		versionKey: "latestWindowsVersion",
	},
	{
		platform: "linux",
		label: "Linux",
		icon: linuxIcon,
		versionKey: "latestLinuxVersion",
	},
	{
		platform: "meta",
		label: "Meta Quest",
		icon: metaIcon,
		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));
};
