import type { PageServerLoad } from './$types';
import * as cache from '$lib/server/cache';

export interface Release {
	id: number;
	tag_name: string;
	name: string;
	body: string;
	published_at: string;
	prerelease: boolean;
	draft: boolean;
}

const GITEA_RELEASES_URL =
	'https://gitea.kalekber.cc/api/v1/repos/kamil/libnovel/releases?limit=50&page=1';

const CACHE_KEY = 'admin:changelog:releases';
const CACHE_TTL = 5 * 60; // 5 minutes

export const load: PageServerLoad = async ({ fetch }) => {
	const cached = await cache.get<Release[]>(CACHE_KEY);
	if (cached) {
		return { releases: cached };
	}

	try {
		const res = await fetch(GITEA_RELEASES_URL, {
			headers: { Accept: 'application/json' }
		});
		if (!res.ok) {
			return { releases: [], error: `Gitea API returned ${res.status}` };
		}
		const releases: Release[] = await res.json();
		const filtered = releases.filter((r) => !r.draft);
		await cache.set(CACHE_KEY, filtered, CACHE_TTL);
		return { releases: filtered };
	} catch (e) {
		return { releases: [], error: String(e) };
	}
};
