import type { CreateSnapshotDto, SnapshotTask } from '@/types/snapshot.types';

/** snapshot-service 请求 — 走 Next.js rewrites 代理 */
async function snapshotFetch<T>(url: string, options?: RequestInit): Promise<T> {
  const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
  const res = await fetch(`/api/snapshots${url}`, {
    headers: {
      'Content-Type': 'application/json',
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    ...options,
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({ message: res.statusText }));
    throw new Error(err.message || `请求失败: ${res.status}`);
  }
  return res.json();
}

export const snapshotApi = {
  getTargets: () =>
    snapshotFetch<{ targets: string[]; isRunning: boolean }>('/snapshots/targets'),

  create: (data: CreateSnapshotDto) =>
    snapshotFetch<{ taskId: string; message: string }>('/snapshots', {
      method: 'POST',
      body: JSON.stringify(data),
    }),

  list: (page = 1, limit = 20) =>
    snapshotFetch<{ tasks: SnapshotTask[]; total: number; page: number; limit: number }>(
      `/snapshots?page=${page}&limit=${limit}`,
    ),

  getById: (id: string) => snapshotFetch<SnapshotTask>(`/snapshots/${id}`),

  delete: (id: string) =>
    snapshotFetch<{ message: string }>(`/snapshots/${id}`, { method: 'DELETE' }),

  getDownloadUrl: (id: string, target: string) =>
    `/api/snapshots/snapshots/${id}/download/${target}`,
};
