import { describe, expect, it, vi } from "vitest";

import { RealAmapAdapter } from "../../apps/api/src/amap-adapter.js";
import { initializeApiCredentialClients } from "../../apps/api/src/supervisor-channel.js";

describe("TDD-WP7-EXT-003 production Amap adapter", () => {
  it("uses the fixed HTTPS provider boundary and returns only the formatted location", async () => {
    const request = vi.fn(async () => ({
      regeocode: { formatted_address: "模拟省模拟市" },
      status: "1",
    }));
    const adapter = new RealAmapAdapter("fixture-amap-value", { request });

    await expect(adapter.reverseGeocode({ latitude: 12.3456, longitude: 65.4321 })).resolves.toEqual({
      formattedValue: "模拟省模拟市",
      serviceMode: "real",
    });
    expect(request).toHaveBeenCalledOnce();
    expect(request.mock.calls[0]?.[0]).toMatchObject({
      allowRedirects: false,
      hostname: "restapi.amap.com",
      maxResponseBytes: 65_536,
      method: "GET",
      protocol: "https:",
      rejectUnauthorized: true,
      timeoutMs: 15_000,
    });
    expect(request.mock.calls[0]?.[0].path).toContain("/v3/geocode/regeo?");
    expect(request.mock.calls[0]?.[0].path).toContain("location=65.4321%2C12.3456");
    adapter.dispose();
    await expect(adapter.reverseGeocode({ latitude: 0, longitude: 0 })).rejects.toThrow("amap_adapter_disposed");
  });

  it("constructs the real client from the API credential channel and clears the source values", () => {
    const credentials = {
      "Dada/P0A/admin/pepper": "fixture-admin-value",
      "Dada/P0A/api/amap": "fixture-amap-value",
      "Dada/P0A/api/resend": "fixture-resend-value",
    };

    const clients = initializeApiCredentialClients(credentials);
    expect(clients.amap).toBeInstanceOf(RealAmapAdapter);
    expect(clients.resendConfigured).toBe(true);
    expect(Object.values(credentials)).toEqual(["", "", ""]);
    clients.amap.dispose?.();
    clients.adminAllowlistPepper.fill(0);
  });

  it("reports an empty Resend credential without retaining its value", () => {
    const credentials = {
      "Dada/P0A/admin/pepper": "fixture-admin-value",
      "Dada/P0A/api/amap": "",
      "Dada/P0A/api/resend": "",
    };

    const clients = initializeApiCredentialClients(credentials);
    expect(clients.resendConfigured).toBe(false);
    expect(Object.values(credentials)).toEqual(["", "", ""]);
    clients.amap.dispose?.();
    clients.adminAllowlistPepper.fill(0);
  });
});
