import type { ApiResponse } from "@/lib/api"

export const PHP_API_BASE_URL =
  import.meta.env.VITE_PHP_API_BASE_URL ?? "https://php-api.juip.com"

const DEFAULT_TIMEOUT = 30_000

export type LineItem = {
  city: string | number
  daikuan: string | number
  name: string | number
  nasname: string | number
  online: string | number
  supply: string | number
}

export type LineData = {
  count: number | string
  use_count: number | string
  data: LineItem[]
}

export type LineSearchResult = {
  data: LineItem[]
}

async function getJson<T>(url: string): Promise<ApiResponse<T>> {
  const controller = new AbortController()
  const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT)
  try {
    const response = await fetch(url, { signal: controller.signal })
    if (!response.ok) {
      return {
        success: false,
        status: response.status,
        message: "请求失败",
      }
    }
    const data = (await response.json()) as T
    return { success: true, data }
  } catch (e) {
    if (controller.signal.aborted) {
      return {
        success: false,
        status: 408,
        message: "请求超时，请稍后重试",
      }
    }
    return {
      success: false,
      status: 500,
      message: (e as Error).message || "网络错误",
    }
  } finally {
    clearTimeout(timer)
  }
}

export function fetchLineData(product: number): Promise<ApiResponse<LineData>> {
  return getJson<LineData>(
    `${PHP_API_BASE_URL}/script/linedata/display.php?product=${product}`,
  )
}

export function searchLineData(
  productid: number,
  info: string,
): Promise<ApiResponse<LineSearchResult>> {
  const query = `type=0&productid=${productid}&info=${encodeURIComponent(info)}`
  return getJson<LineSearchResult>(
    `${PHP_API_BASE_URL}/script/linedata/search.php?${query}`,
  )
}
