import { createHmac } from "node:crypto";
import { describe, expect, it } from "vitest";
import { DlocalAdapter } from "./dlocal.adapter";

const credentials = {
  apiKey: "login",
  secretKey: "supersecret",
};

function build() {
  return new DlocalAdapter({
    baseUrl: "http://unused.local",
    mode: "sandbox",
    credentials,
  });
}

describe("DlocalAdapter.parseWebhook", () => {
  it("accepts a body with valid HMAC-SHA256 signature", () => {
    const adapter = build();
    const body = JSON.stringify({ id: "D-12345", status: "PAID" });
    const sig = createHmac("sha256", credentials.secretKey).update(body).digest("hex");
    const result = adapter.parseWebhook(body, { "x-dlocalgo-signature": sig });
    expect(result).not.toBeNull();
    expect(result?.providerPaymentId).toBe("D-12345");
    expect(result?.status).toBe("approved");
  });

  it("rejects a body whose signature was computed with another secret", () => {
    const adapter = build();
    const body = JSON.stringify({ id: "D-99", status: "PAID" });
    const wrong = createHmac("sha256", "another").update(body).digest("hex");
    expect(adapter.parseWebhook(body, { "x-dlocalgo-signature": wrong })).toBeNull();
  });

  it("rejects when signature header is absent", () => {
    expect(build().parseWebhook("{}", {})).toBeNull();
  });

  it("rejects malformed JSON even when signature is valid", () => {
    const adapter = build();
    const body = "not-json";
    const sig = createHmac("sha256", credentials.secretKey).update(body).digest("hex");
    expect(adapter.parseWebhook(body, { "x-dlocalgo-signature": sig })).toBeNull();
  });

  it("maps PENDING / REJECTED / EXPIRED correctly", () => {
    const adapter = build();
    const cases: Array<[string, string]> = [
      ["PENDING", "pending"],
      ["REJECTED", "rejected"],
      ["EXPIRED", "expired"],
      ["AUTHORIZED", "processing"],
    ];
    for (const [providerStatus, expected] of cases) {
      const body = JSON.stringify({ id: "x", status: providerStatus });
      const sig = createHmac("sha256", credentials.secretKey).update(body).digest("hex");
      expect(adapter.parseWebhook(body, { "x-dlocalgo-signature": sig })?.status).toBe(expected);
    }
  });
});
