/**
 * 日志拦截器
 *
 * 在开发模式下记录请求/响应/错误日志。
 * 
 */
import type { FetchHook } from "ofetch";

import { AppEnvUtil, Logger } from "@/utils";

const log = new Logger("ApiLoggingInterceptor");

function getRequestUrl(request: Request | string): string {
  return typeof request === "string" ? request : request.url;
}

function getRequestMethod(
  request: Request | string,
  options: { method?: string }
): string {
  return request instanceof Request ? request.method : options.method ?? "GET";
}

export const onRequestLogging: FetchHook = async (ctx) => {
  if (AppEnvUtil.isProduction()) return;
  const method = getRequestMethod(ctx.request, ctx.options);
  const url = getRequestUrl(ctx.request);
  const body = Logger.formatValue(ctx.options.body);
  log.debug(`→ ${method} ${url}${body ? `\nrequest body:\n${body}` : ""}`);
};

export const onResponseLogging: FetchHook = async (ctx) => {
  if (AppEnvUtil.isProduction() || !ctx.response) return;
  const method = getRequestMethod(ctx.request, ctx.options);
  const url = getRequestUrl(ctx.request);
  const body = Logger.formatValue(ctx.response._data);
  log.debug(
    `← ${ctx.response.status} ${method} ${url}${body ? `\nresponse body:\n${body}` : ""}`,
  );
};

export const onErrorLogging: FetchHook = async (ctx) => {
  if (AppEnvUtil.isProduction()) return;
  const status = ctx.response?.status ?? "N/A";
  const method = getRequestMethod(ctx.request, ctx.options);
  const url = getRequestUrl(ctx.request);
  const body = Logger.formatValue(ctx.response?._data);
  log.error(
    `✕ ${status} ${method} ${url}\nerror: ${ctx.error?.message ?? "Unknown error"}${body ? `\nresponse body:\n${body}` : ""}`,
  );
};

/**
 * 兼容旧接口的 FetchHooks 形式（保留以备兼容）
 */
export const loggingInterceptor = {
  onRequest: onRequestLogging,
  onResponse: onResponseLogging,
  onResponseError: onErrorLogging,
  onRequestError: onErrorLogging,
};
