// R2 credential smoke test: put a tiny CSV → read_csv via DuckDB (r2:// secret) → delete.
// Run: cd services/analytics && bun --env-file=../../.env.local run scripts/r2-smoke.ts
import { DuckDBInstance } from "@duckdb/node-api";
import { S3Client } from "bun";

const accountId = process.env.R2_ACCOUNT_ID;
const bucket = process.env.R2_BUCKET;
if (!accountId || !bucket) throw new Error("R2_ACCOUNT_ID / R2_BUCKET missing");

const s3 = new S3Client({
  accessKeyId: process.env.R2_ACCESS_KEY_ID,
  secretAccessKey: process.env.R2_SECRET_ACCESS_KEY,
  bucket,
  endpoint: `https://${accountId}.r2.cloudflarestorage.com`,
  region: "auto",
});

const key = "smoke/r2-smoke.csv";
const csv = "Keyword,Volume\nhello world,1234\n";

console.log(`[1/4] PUT s3://${bucket}/${key} …`);
await s3.file(key).write(csv, { type: "text/csv" });
console.log("      ok");

console.log("[2/4] DuckDB read_csv('r2://…') …");
const inst = await DuckDBInstance.create(":memory:");
const c = await inst.connect();
const q = (s: string | undefined) => `'${(s ?? "").replace(/'/g, "''")}'`;
await c.runAndReadAll("INSTALL httpfs");
await c.runAndReadAll("LOAD httpfs");
await c.runAndReadAll(
  `CREATE OR REPLACE SECRET r2 (TYPE R2, KEY_ID ${q(process.env.R2_ACCESS_KEY_ID)}, SECRET ${q(process.env.R2_SECRET_ACCESS_KEY)}, ACCOUNT_ID ${q(accountId)})`,
);
const reader = await c.runAndReadAll(
  `select * from read_csv('r2://${bucket}/${key}', header=true, all_varchar=true)`,
);
const rows = reader.getRowObjects();
console.log("      rows:", JSON.stringify(rows));
if (rows.length !== 1 || String(rows[0].Volume) !== "1234")
  throw new Error("read_csv returned unexpected rows");

console.log("[3/4] DELETE …");
await s3.file(key).delete();
console.log("      ok");

console.log("[4/4] verify gone …");
const exists = await s3.file(key).exists();
if (exists) throw new Error("object still present after delete");

console.log(
  "\nR2_SMOKE_OK — put/read/delete round-trip passed against the live bucket.",
);
