import test from "node:test";
import assert from "node:assert/strict";
import { BlinkInvoiceService } from "./BlinkInvoiceService";

test("creates a normalized Lightning invoice response", async () => {
  const savedRecords: Array<Record<string, unknown>> = [];
  const service = new BlinkInvoiceService(
    {
      async getBtcWalletId() {
        return "btc-wallet-id";
      },
      async createLightningInvoice(input) {
        assert.equal(input.amount, 2500);
        assert.equal(input.walletId, "btc-wallet-id");
        assert.equal(input.externalId, "dep_ref_123");

        return {
          createdAt: 1_715_000_000,
          externalId: "dep_ref_123",
          paymentHash: "hash_123",
          paymentRequest: "lnbc25u1test",
          paymentStatus: "PENDING",
          satoshis: 2500,
        };
      },
    },
    {
      async savePending(record) {
        savedRecords.push(record as unknown as Record<string, unknown>);
      },
      async findPendingByPaymentHashOrReference() {
        return null;
      },
      async markConfirmed() {
        return;
      },
    },
    { defaultExpiresInMinutes: 30 }
  );

  const response = await service.createInvoice({
    user_id: 42,
    amount_sats: 2500,
    currency: "BTC",
    reference: "dep_ref_123",
  });

  assert.deepEqual(response, {
    provider: "blink",
    network: "bitcoin_lightning",
    asset: "BTC",
    payment_request: "lnbc25u1test",
    payment_hash: "hash_123",
    amount_sats: 2500,
    expires_at: "2024-05-06T13:23:20.000Z",
    reference: "dep_ref_123",
  });
  assert.equal(savedRecords.length, 1);
  assert.equal(savedRecords[0].status, "pending");
});

test("rejects unsupported invoice currencies", async () => {
  const service = new BlinkInvoiceService({
    async getBtcWalletId() {
      return "btc-wallet-id";
    },
    async createLightningInvoice() {
      throw new Error("should not be called");
    },
  }, {
    async savePending() {
      return;
    },
    async findPendingByPaymentHashOrReference() {
      return null;
    },
    async markConfirmed() {
      return;
    },
  });

  await assert.rejects(
    () =>
      service.createInvoice({
        user_id: 42,
        amount_sats: 2500,
        currency: "USD",
        reference: "dep_ref_123",
      }),
    /currency must be BTC/
  );
});
