import type { DailyResponse } from '@wordle/shared';
import { getApiBase } from './messages/index.js';

function base() { return getApiBase(); }

async function fetchJSON<T>(url: string, options?: RequestInit): Promise<T> {
  const res = await fetch(url, options);
  if (!res.ok) {
    const body = await res.json().catch(() => ({}));
    throw new Error((body as { error?: string }).error ?? `HTTP ${res.status}`);
  }
  return res.json() as Promise<T>;
}

export function getDaily(): Promise<DailyResponse> {
  return fetchJSON<DailyResponse>(`${base()}/daily`);
}

export function postGuess(body: { wordId: number; guess: string; tryNo: number }): Promise<import('@wordle/shared').GuessResponse> {
  return fetchJSON(`${base()}/guess`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}

export function postPlayAgain(body: { skillMetric: number }): Promise<import('@wordle/shared').PlayAgainResponse> {
  return fetchJSON(`${base()}/play-again`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
}
