import type { CfAccount } from "../types";
import { LEGACY_STORAGE_ACCOUNTS } from "../constants";

export async function apiVerify(token: string): Promise<boolean> {
  const r = await fetch("/api/verify", { headers: { "X-App-Token": token } });
  return r.ok;
}

/** 调用 Cloudflare API（经 Worker /api/cf 代理） */
export async function cfRequest(
  appToken: string,
  accountApiToken: string,
  path: string,
  init: RequestInit = {},
): Promise<unknown> {
  const headers = new Headers(init.headers);
  headers.set("X-App-Token", appToken);
  headers.set("Authorization", `Bearer ${accountApiToken}`);
  const r = await fetch(`/api/cf${path}`, { ...init, headers });
  const text = await r.text();
  let json: Record<string, unknown> = {};
  try {
    json = text ? (JSON.parse(text) as Record<string, unknown>) : {};
  } catch {
    throw new Error(`接口返回非 JSON：${r.status}`);
  }
  if (!r.ok || json.success === false) {
    const errs = json.errors as Array<{ message?: string; code?: string }> | undefined;
    const msgs = json.messages as string[] | undefined;
    const msg =
      errs?.map((e) => e.message || e.code).join("；") ||
      msgs?.join?.("；") ||
      `请求失败 (${r.status})`;
    throw new Error(msg);
  }
  return json;
}

export async function fetchAccountsApi(appToken: string): Promise<CfAccount[]> {
  const r = await fetch("/api/accounts", { headers: { "X-App-Token": appToken } });
  const text = await r.text();
  let data: { accounts?: CfAccount[]; errors?: { message: string }[] } = {};
  try {
    data = text ? JSON.parse(text) : {};
  } catch {
    /* ignore */
  }
  if (!r.ok) {
    const msg =
      data.errors?.map((e) => e.message).join("；") || `加载账号失败 (${r.status})`;
    throw new Error(msg);
  }
  return Array.isArray(data.accounts) ? data.accounts : [];
}

/** 将旧版 localStorage 账号迁入 D1；若执行过迁入返回 true */
export async function migrateLegacyAccountsIfNeeded(appToken: string): Promise<boolean> {
  const raw = localStorage.getItem(LEGACY_STORAGE_ACCOUNTS);
  if (!raw) return false;
  let list: unknown;
  try {
    list = JSON.parse(raw);
  } catch {
    return false;
  }
  if (!Array.isArray(list) || !list.length) return false;
  for (const a of list) {
    const row = a as { name?: string; token?: string };
    if (!row?.token) continue;
    const r = await fetch("/api/accounts", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-App-Token": appToken,
      },
      body: JSON.stringify({
        name: row.name || "账号",
        token: String(row.token),
      }),
    });
    if (!r.ok) {
      const t = await r.text();
      let err = t;
      try {
        err = (JSON.parse(t) as { errors?: { message: string }[] }).errors?.[0]?.message || t;
      } catch {
        /* keep */
      }
      throw new Error(`迁移旧数据失败：${err}`);
    }
  }
  localStorage.removeItem(LEGACY_STORAGE_ACCOUNTS);
  return true;
}
