import { CapacitorHttp, type HttpOptions, type HttpResponse } from "@capacitor/core";
import type { HttpTransport } from "../src/core/politeCore.js";

export type CapacitorRequest = (options: HttpOptions) => Promise<HttpResponse>;

/** Adapts Capacitor's native URLConnection transport to the shared politeness core. */
export function createCapacitorHttpTransport(
  request: CapacitorRequest = (options) => CapacitorHttp.request(options),
): HttpTransport {
  return async (input) => {
    const response = await request({
      url: input.url,
      method: input.method,
      headers: input.headers,
      ...(input.body === undefined ? {} : { data: input.body }),
      responseType: "text",
      connectTimeout: input.timeoutMs,
      readTimeout: input.timeoutMs,
    });
    return {
      status: response.status,
      headers: response.headers,
      // Capacitor's Android implementation eagerly decodes application/json even
      // with responseType="text". The transport contract still guarantees text;
      // JSON adapters parse this normalized representation immediately.
      body:
        response.data === undefined || response.data === null
          ? ""
          : typeof response.data === "string"
            ? response.data
            : JSON.stringify(response.data),
    };
  };
}
