import { API_BASE } from '../config/site';
import type { Site } from '../types/site';

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

export async function fetchSites(init?: RequestInit): Promise<Site[]> {
  const r = await fetch(url('/api/sites'), init);
  if (!r.ok) throw new Error('加载网站失败');
  return r.json();
}

export async function postSiteClick(siteId: string): Promise<void> {
  await fetch(url(`/api/sites/${siteId}/click`), { method: 'POST', keepalive: true }).catch(() => {});
}

export async function authLogin(password: string): Promise<{ ok: boolean; sessionId?: string }> {
  const r = await fetch(url('/api/auth/login'), {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ password }),
  });
  const data = await r.json().catch(() => ({}));
  if (!r.ok || !data?.ok || !data?.sessionId) return { ok: false };
  return { ok: true, sessionId: data.sessionId as string };
}

export async function authCheck(token: string): Promise<boolean> {
  const r = await fetch(url('/api/auth/check'), {
    headers: { Authorization: `Bearer ${token}` },
  });
  if (r.status !== 200) return false;
  const data = await r.json().catch(() => ({}));
  return Boolean(data?.ok);
}

export async function fetchCategories(token: string): Promise<string[]> {
  const r = await fetch(url('/api/categories'), {
    headers: { Authorization: `Bearer ${token}` },
  });
  if (r.status === 401) throw new Error('unauthorized');
  if (!r.ok) return [];
  return r.json();
}

export async function fetchSiteById(id: string): Promise<Site> {
  const r = await fetch(url(`/api/sites/${id}`));
  if (!r.ok) throw new Error('加载站点失败');
  return r.json();
}

export async function saveSite(token: string, site: Partial<Site>, id?: string): Promise<boolean> {
  const path = id ? `/api/sites/${id}` : '/api/sites';
  const method = id ? 'PUT' : 'POST';
  const r = await fetch(url(path), {
    method,
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify(site),
  });
  return r.ok;
}

export async function deleteSite(token: string, id: string): Promise<boolean> {
  const r = await fetch(url(`/api/sites/${id}`), {
    method: 'DELETE',
    headers: { Authorization: `Bearer ${token}` },
  });
  return r.ok;
}

export async function addCategory(token: string, name: string): Promise<boolean> {
  const r = await fetch(url('/api/categories'), {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify({ name }),
  });
  return r.ok;
}

export async function renameCategory(token: string, oldName: string, newName: string): Promise<boolean> {
  const r = await fetch(url(`/api/categories/${encodeURIComponent(oldName)}`), {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify({ name: newName }),
  });
  return r.ok;
}

export async function deleteCategory(token: string, name: string): Promise<boolean> {
  const r = await fetch(url(`/api/categories/${encodeURIComponent(name)}`), {
    method: 'DELETE',
    headers: { Authorization: `Bearer ${token}` },
  });
  return r.ok;
}
