import type { Cookies } from '@sveltejs/kit';
import { dev } from '$app/environment';

const OPENID_ENDPOINT = 'https://steamcommunity.com/openid/login';

const STEAM_ID_COOKIE = 'steam_id64';

function cookieOptions() {
  return {
    path: '/',
    httpOnly: true as const,
    sameSite: 'lax' as const,
    secure: dev ? false : true,
    maxAge: 30 * 24 * 3600
  };
}

export function setSteamIdCookie(cookies: Cookies, steamId64: string): void {
  cookies.set(STEAM_ID_COOKIE, steamId64, cookieOptions());
}

export function getSteamIdFromCookies(cookies: Cookies): string | null {
  return cookies.get(STEAM_ID_COOKIE) ?? null;
}

export function clearSteamCookie(cookies: Cookies): void {
  cookies.delete(STEAM_ID_COOKIE, cookieOptions());
}

export function buildSteamOpenIDLoginUrl(origin: string, redirectTo?: string | null): URL {
  const returnTo = new URL('/auth/steam/callback', origin);
  if (redirectTo) returnTo.searchParams.set('redirect_uri', redirectTo);

  const realm = origin;

  const url = new URL(OPENID_ENDPOINT);
  url.searchParams.set('openid.ns', 'http://specs.openid.net/auth/2.0');
  url.searchParams.set('openid.mode', 'checkid_setup');
  url.searchParams.set('openid.return_to', returnTo.toString());
  url.searchParams.set('openid.realm', realm);
  url.searchParams.set('openid.identity', 'http://specs.openid.net/auth/2.0/identifier_select');
  url.searchParams.set('openid.claimed_id', 'http://specs.openid.net/auth/2.0/identifier_select');
  return url;
}

export async function verifySteamOpenIDResponse(searchParams: URLSearchParams): Promise<string | null> {
  // Steam expects the exact parameters back with mode switched to check_authentication
  const params = new URLSearchParams();
  for (const [key, value] of searchParams.entries()) {
    if (key === 'openid.mode') continue;
    if (!key.startsWith('openid.')) continue;
    params.set(key, value);
  }
  params.set('openid.mode', 'check_authentication');

  const res = await fetch(OPENID_ENDPOINT, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: params
  });
  if (!res.ok) return null;
  const text = await res.text();
  if (!/is_valid\s*:\s*true/.test(text)) return null;

  const claimed = searchParams.get('openid.claimed_id') || '';
  // Expected format: https://steamcommunity.com/openid/id/7656119...
  const m = claimed.match(/\/id\/(\d+)$/);
  if (!m) return null;
  return m[1];
}


