import type { Cookies } from '@sveltejs/kit';
import {
	ACCESS_TOKEN_CHUNK_COUNT,
	accessTokenChunkName,
	splitAccessTokenForCookies,
	ACCESS_TOKEN_MAX_CHUNKS
} from '$lib/access-token-cookie.shared';

export function getAccessTokenFromCookies(cookies: Cookies): string | null {
	const countRaw = cookies.get(ACCESS_TOKEN_CHUNK_COUNT);
	if (countRaw) {
		const n = parseInt(countRaw, 10);
		if (!Number.isFinite(n) || n < 1 || n > ACCESS_TOKEN_MAX_CHUNKS) return null;
		let out = '';
		for (let i = 0; i < n; i++) {
			const p = cookies.get(accessTokenChunkName(i));
			if (p == null) return null;
			out += p;
		}
		return out;
	}
	return cookies.get('access_token') ?? null;
}

export function clearAccessTokenCookies(cookies: Cookies) {
	cookies.delete('access_token', { path: '/' });
	cookies.delete(ACCESS_TOKEN_CHUNK_COUNT, { path: '/' });
	for (let i = 0; i < ACCESS_TOKEN_MAX_CHUNKS; i++) {
		cookies.delete(accessTokenChunkName(i), { path: '/' });
	}
}

export function setAccessTokenCookies(
	cookies: Cookies,
	token: string,
	opts: { secure: boolean; maxAge: number }
) {
	clearAccessTokenCookies(cookies);
	const split = splitAccessTokenForCookies(token);
	const base = {
		path: '/',
		httpOnly: false as const,
		sameSite: 'lax' as const,
		secure: opts.secure,
		maxAge: opts.maxAge
	};
	if (split.kind === 'single') {
		cookies.set('access_token', split.value, base);
		return;
	}
	cookies.set(ACCESS_TOKEN_CHUNK_COUNT, String(split.parts.length), base);
	split.parts.forEach((part, i) => {
		cookies.set(accessTokenChunkName(i), part, base);
	});
}
