// === API client for backend communication ===
import type {
  VideoListItem,
  VideoDetail,
  ProcessRequest,
  ProcessResponse,
  JobInfo,
} from './types';

// Backend URL - use relative URLs for proxy support (ngrok, etc.)
// Next.js rewrites /api/* to backend at localhost:8000
// This allows frontend and backend to be accessed via single tunnel
function getApiBase(): string {
  // Use empty string for relative URLs - works with Next.js rewrites
  // Requests to /api/* will be proxied to localhost:8000/api/*
  return '';
}

const API_BASE = getApiBase();

// === Video endpoints ===

export async function listVideos(): Promise<VideoListItem[]> {
  const res = await fetch(`${API_BASE}/api/videos`);
  if (!res.ok) throw new Error(`Failed to list videos: ${res.statusText}`);
  return res.json();
}

export async function getVideoDetails(videoId: string): Promise<VideoDetail> {
  const res = await fetch(`${API_BASE}/api/videos/${videoId}`);
  if (!res.ok) throw new Error(`Failed to get video: ${res.statusText}`);
  return res.json();
}

export function getVideoStreamUrl(videoId: string): string {
  return `${API_BASE}/api/videos/${videoId}/stream`;
}

export function getAudioStreamUrl(videoId: string): string {
  return `${API_BASE}/api/videos/${videoId}/audio`;
}

export function getThumbnailUrl(videoId: string): string {
  return `${API_BASE}/api/videos/${videoId}/thumbnail`;
}

export function getDownloadZipUrl(videoId: string): string {
  return `${API_BASE}/api/videos/${videoId}/download`;
}

// === Processing endpoints ===

export async function processVideo(request: ProcessRequest): Promise<ProcessResponse> {
  const res = await fetch(`${API_BASE}/api/process`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(request),
  });
  if (!res.ok) {
    const error = await res.json().catch(() => ({ detail: res.statusText }));
    throw new Error(error.detail || 'Failed to start processing');
  }
  return res.json();
}

export async function getJobStatus(jobId: string): Promise<JobInfo> {
  const res = await fetch(`${API_BASE}/api/jobs/${jobId}`);
  if (!res.ok) throw new Error(`Failed to get job status: ${res.statusText}`);
  return res.json();
}

// === Health check ===

export async function healthCheck(): Promise<boolean> {
  try {
    const res = await fetch(`${API_BASE}/api/health`);
    return res.ok;
  } catch {
    return false;
  }
}

// === Export API_BASE for direct use in components ===
export { API_BASE };
