/**
 * API client for the assessment backend.
 */

import type {
  DimensionDefinitions,
  QueryInfo,
  QueryWithIdeas,
  Rater,
  RaterCreate,
  RaterProgress,
  Rating,
  RatingSubmit,
  SessionInfo,
  Statistics,
} from '../types';

const API_BASE = '/api';

async function fetchJson<T>(url: string, options?: RequestInit): Promise<T> {
  const response = await fetch(`${API_BASE}${url}`, {
    headers: {
      'Content-Type': 'application/json',
      ...options?.headers,
    },
    ...options,
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ detail: response.statusText }));
    throw new Error(error.detail || 'API request failed');
  }

  return response.json();
}

// Rater API
export async function listRaters(): Promise<Rater[]> {
  return fetchJson<Rater[]>('/raters');
}

export async function createOrGetRater(data: RaterCreate): Promise<Rater> {
  return fetchJson<Rater>('/raters', {
    method: 'POST',
    body: JSON.stringify(data),
  });
}

export async function getRater(raterId: string): Promise<Rater> {
  return fetchJson<Rater>(`/raters/${encodeURIComponent(raterId)}`);
}

// Query API
export async function listQueries(): Promise<QueryInfo[]> {
  return fetchJson<QueryInfo[]>('/queries');
}

export async function getQueryWithIdeas(queryId: string): Promise<QueryWithIdeas> {
  return fetchJson<QueryWithIdeas>(`/queries/${encodeURIComponent(queryId)}`);
}

export async function getUnratedIdeas(queryId: string, raterId: string): Promise<QueryWithIdeas> {
  return fetchJson<QueryWithIdeas>(
    `/queries/${encodeURIComponent(queryId)}/unrated?rater_id=${encodeURIComponent(raterId)}`
  );
}

// Rating API
export async function submitRating(rating: RatingSubmit): Promise<{ saved: boolean }> {
  return fetchJson<{ saved: boolean }>('/ratings', {
    method: 'POST',
    body: JSON.stringify(rating),
  });
}

export async function getRating(raterId: string, ideaId: string): Promise<Rating | null> {
  try {
    return await fetchJson<Rating>(`/ratings/${encodeURIComponent(raterId)}/${encodeURIComponent(ideaId)}`);
  } catch {
    return null;
  }
}

export async function getRatingsByRater(raterId: string): Promise<Rating[]> {
  return fetchJson<Rating[]>(`/ratings/rater/${encodeURIComponent(raterId)}`);
}

// Progress API
export async function getRaterProgress(raterId: string): Promise<RaterProgress> {
  return fetchJson<RaterProgress>(`/progress/${encodeURIComponent(raterId)}`);
}

// Statistics API
export async function getStatistics(): Promise<Statistics> {
  return fetchJson<Statistics>('/statistics');
}

// Dimension definitions API
export async function getDimensionDefinitions(): Promise<DimensionDefinitions> {
  return fetchJson<DimensionDefinitions>('/dimensions');
}

// Session info API
export async function getSessionInfo(): Promise<SessionInfo> {
  return fetchJson<SessionInfo>('/info');
}

// Health check
export async function healthCheck(): Promise<boolean> {
  try {
    await fetchJson<{ status: string }>('/health');
    return true;
  } catch {
    return false;
  }
}
