import { describe, expect, it, vi } from "vitest";
import { createCapacitorHttpTransport } from "../android/capacitorHttpTransport.js";

describe("createCapacitorHttpTransport", () => {
  it("maps the portable request to native timeouts and preserves a text response", async () => {
    const request = vi.fn().mockResolvedValue({
      status: 200,
      headers: { "content-type": "text/html" },
      data: "<html>ok</html>",
      url: "https://partsale.lv/search",
    });
    const transport = createCapacitorHttpTransport(request);

    await expect(transport({
      url: "https://partsale.lv/search",
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      body: "q=W71252",
      timeoutMs: 12_000,
    })).resolves.toEqual({
      status: 200,
      headers: { "content-type": "text/html" },
      body: "<html>ok</html>",
    });
    expect(request).toHaveBeenCalledWith({
      url: "https://partsale.lv/search",
      method: "POST",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      data: "q=W71252",
      responseType: "text",
      connectTimeout: 12_000,
      readTimeout: 12_000,
    });
  });

  it("normalizes Capacitor-decoded JSON back to adapter input text", async () => {
    const transport = createCapacitorHttpTransport(async () => ({
      status: 200,
      headers: { "content-type": "application/json" },
      data: { offers: [1] },
      url: "https://example.test/api",
    }));

    const response = await transport({
      url: "https://example.test/api",
      method: "GET",
      headers: {},
      timeoutMs: 8_000,
    });
    expect(response.body).toBe('{"offers":[1]}');
  });

  it.each([undefined, null])("maps an absent native body (%s) to an empty string", async (data) => {
    const transport = createCapacitorHttpTransport(async () => ({
      status: 204,
      headers: {},
      data,
      url: "https://example.test/empty",
    }));

    await expect(transport({
      url: "https://example.test/empty",
      method: "GET",
      headers: {},
      timeoutMs: 8_000,
    })).resolves.toMatchObject({ body: "" });
  });
});
