import type { SearchPreset, SearchPipelineConfig } from '@/types';

const DEFAULT_AUTOMATION_PORT = '3030';

function trimTrailingSlash(value: string): string {
  return value.replace(/\/+$/, '');
}

function resolveBaseUrl(): string {
  const explicit = import.meta.env.VITE_AUTOMATION_BASE_URL?.trim();
  if (explicit) return trimTrailingSlash(explicit);
  if (import.meta.env.DEV) return '';

  if (typeof window !== 'undefined') {
    if (!import.meta.env.VITE_AUTOMATION_PORT) {
      return trimTrailingSlash(window.location.origin);
    }

    return `${window.location.protocol}//${window.location.hostname}:${import.meta.env.VITE_AUTOMATION_PORT}`;
  }

  return `http://127.0.0.1:${import.meta.env.VITE_AUTOMATION_PORT ?? DEFAULT_AUTOMATION_PORT}`;
}

const BASE_URL = resolveBaseUrl();

function url(path: string) {
  return `${BASE_URL}${path}`;
}

export async function fetchSearchPresets(userId: string): Promise<SearchPreset[]> {
  const res = await fetch(url(`/api/search-presets?user_id=${encodeURIComponent(userId)}`));
  if (!res.ok) {
    const body = await res.json().catch(() => ({ error: '请求失败' }));
    throw new Error(body.error ?? `HTTP ${res.status}`);
  }
  return res.json();
}

export async function createSearchPreset(params: {
  user_id: string;
  name: string;
  config: SearchPipelineConfig;
  is_default?: boolean;
}): Promise<SearchPreset> {
  const res = await fetch(url('/api/search-presets'), {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({ error: '请求失败' }));
    throw new Error(body.error ?? `HTTP ${res.status}`);
  }
  return res.json();
}

export async function updateSearchPreset(
  id: string,
  params: { name?: string; config?: SearchPipelineConfig; is_default?: boolean },
): Promise<SearchPreset> {
  const res = await fetch(url(`/api/search-presets/${encodeURIComponent(id)}`), {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(params),
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({ error: '请求失败' }));
    throw new Error(body.error ?? `HTTP ${res.status}`);
  }
  return res.json();
}

export async function deleteSearchPreset(id: string): Promise<void> {
  const res = await fetch(url(`/api/search-presets/${encodeURIComponent(id)}`), {
    method: 'DELETE',
  });
  if (!res.ok) {
    const body = await res.json().catch(() => ({ error: '请求失败' }));
    throw new Error(body.error ?? `HTTP ${res.status}`);
  }
}
