export interface StatsData {
	solveRank: number;
	guessRank: number;
	totalSolves: number;
	averageGuesses: number;
	tiedCount: number;
	percentile: number;
	guesses?: string[]; // Present when fetching an existing completion (cross-device sync)
}

export async function submitCompletion(params: {
	anonymousId: string;
	date: string;
	guessCount: number;
	guesses: string[];
}): Promise<StatsData | null> {
	try {
		const response = await fetch("/api/submit-completion", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify(params),
		});

		const result = await response.json();

		if (result.success && result.stats) {
			return result.stats;
		}

		if (response.status === 409) {
			// Already submitted from another device — fetch existing stats
			return fetchExistingStats({ anonymousId: params.anonymousId, date: params.date });
		}

		if (result.error) {
			console.error("Stats server error:", result.error);
		}
		return null;
	} catch (err) {
		console.error("Stats submission failed:", err);
		return null;
	}
}

export async function fetchExistingStats(params: {
	anonymousId: string;
	date: string;
}): Promise<StatsData | null> {
	try {
		const response = await fetch(
			`/api/stats?anonymousId=${params.anonymousId}&date=${params.date}`,
		);

		const result = await response.json();

		if (result.success && result.stats) {
			return result.stats;
		}

		if (result.error) {
			console.error("Stats server error:", result.error);
		}
		return null;
	} catch (err) {
		console.error("Stats fetch failed:", err);
		return null;
	}
}
