import type { AccessLog, GeoDistributionItem, GeoPoint, ScrapeJob, ScrapeJobDetail, ScrapeResult, Stats } from './types';

const BASE = import.meta.env.VITE_API_BASE_URL ?? 'http://localhost:8000';

async function get<T>(path: string): Promise<T> {
  const res = await fetch(`${BASE}${path}`);
  if (!res.ok) throw new Error(`GET ${path} failed: ${res.status}`);
  return res.json() as Promise<T>;
}

export const fetchStats = () => get<Stats>('/api/stats');
export const fetchGeoDistribution = () => get<GeoDistributionItem[]>('/api/geo/distribution');
export const fetchGeoPoints = () => get<GeoPoint[]>('/api/geo/points');
export const fetchLogs = (page = 1, pageSize = 50) =>
  get<AccessLog[]>(`/api/logs?page=${page}&page_size=${pageSize}`);
export const fetchScrapeJobs = () => get<ScrapeJob[]>('/api/scrape');
export const fetchScrapeJob = (jobId: string) => get<ScrapeJobDetail>(`/api/scrape/${jobId}`);
export const fetchPublicPrices = (url?: string) =>
  get<ScrapeResult[]>(`/api/public/prices${url ? `?url=${encodeURIComponent(url)}` : ''}`);
export const fetchTopPriceIps = () =>
  get<{ ip: string; hit_count: number; percentage: number }[]>('/api/prices/top-ips');

export async function postScrape(urls: string[]): Promise<ScrapeJob> {
  const res = await fetch(`${BASE}/api/scrape`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ urls }),
  });
  if (!res.ok) throw new Error(`POST /api/scrape failed: ${res.status}`);
  return res.json() as Promise<ScrapeJob>;
}
