import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
import { readFileSync } from "node:fs";
import { fakeD1 } from "../metering/fake-d1.test-helper";
let d1 = fakeD1();
const fakeEnv: Record<string, unknown> = {
get DB() {
return d1.binding;
},
SECRETS_KEY: "unit-test-secrets-key-0123456789abcdef",
PUBLIC_URL: "https://forge.test",
INTEGRATIONS_ALLOW_LOOPBACK: "false",
MERGEFIX_GATEWAY_ID: "default",
};
mock.module("cloudflare:workers", () => ({ env: fakeEnv, waitUntil: () => undefined }));
const { validateEndpoint, saveEndpoint, endpointSummary, resolveAiEndpoint, resolveAiEndpointSummary, deleteEndpoint } =
await import("./endpoint");
const { chatCompletion, endpointUrl } = await import("../mergefix/gateway");
const migration = readFileSync(new URL("../../../migrations/0032_ai_endpoints.sql", import.meta.url), "utf8");
const realFetch = globalThis.fetch;
beforeEach(() => {
d1 = fakeD1();
d1.db.exec(`CREATE TABLE account_ai_keys (account_id TEXT, provider TEXT, model TEXT, key_ciphertext TEXT,
key_iv TEXT, updated_by TEXT, updated_at INTEGER);`);
d1.db.exec(migration);
d1.db.exec(`
INSERT INTO accounts VALUES ('u1', 'alice', 'user'), ('u2', 'bob', 'user');
INSERT INTO repos VALUES ('r1', 'u1', 'web');
`);
fakeEnv.INTEGRATIONS_ALLOW_LOOPBACK = "false";
});
afterEach(() => {
globalThis.fetch = realFetch;
});
const provider = { kind: "provider", provider: "openai", model: "gpt-4.1-mini", apiKey: "sk-account-key" } as const;