import type { MediaType, Recommendation, RecommendationSummary, FeedbackEntry } from '../types/index.js';

const BASE = '/api';

async function request<T>(path: string, options?: RequestInit): Promise<T> {
  const res = await fetch(`${BASE}${path}`, {
    headers: { 'Content-Type': 'application/json' },
    ...options,
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`HTTP ${res.status}: ${text}`);
  }
  return res.json() as Promise<T>;
}

export function createRecommendation(body: {
  main_prompt: string;
  liked_shows: string;
  disliked_shows: string;
  themes: string;
  brainstorm_count?: number;
  media_type: MediaType;
  use_web_search?: boolean;
}): Promise<{ id: string }> {
  return request('/recommendations', {
    method: 'POST',
    body: JSON.stringify(body),
  });
}

export function listRecommendations(): Promise<RecommendationSummary[]> {
  return request('/recommendations');
}

export function getRecommendation(id: string): Promise<Recommendation> {
  return request(`/recommendations/${id}`);
}

export function rerankRecommendation(id: string): Promise<{ ok: boolean }> {
  return request(`/recommendations/${id}/rerank`, { method: 'POST' });
}

export function submitFeedback(body: {
  item_name: string;
  stars: number;
  feedback?: string;
}): Promise<{ ok: boolean }> {
  return request('/feedback', {
    method: 'POST',
    body: JSON.stringify(body),
  });
}

export function getFeedback(): Promise<FeedbackEntry[]> {
  return request('/feedback');
}
