// Object access for the ETL service. Two drivers:
//   - `local` (tests): objectKey is a filesystem path read directly; never deleted.
//   - `r2`   (default/prod): objectKey is a bucket key; DuckDB reads via the `r2://`
//     scheme (an R2 secret is created in the processor), and we delete via Bun's S3
//     client pointed at the R2 endpoint after a successful import (no retention).
import { S3Client } from "bun";
import { env } from "./env";

const driver = (): "local" | "r2" =>
  env().STORAGE_DRIVER === "local" ? "local" : "r2";

function r2Client(): S3Client {
  const e = env(); // validated: R2_* guaranteed present when driver !== "local"
  return new S3Client({
    accessKeyId: e.R2_ACCESS_KEY_ID,
    secretAccessKey: e.R2_SECRET_ACCESS_KEY,
    bucket: e.R2_BUCKET,
    endpoint: `https://${e.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
    region: "auto",
  });
}

/** A location DuckDB read_csv() can open. local → the path; r2 → an r2:// URL. */
export function resolveReadable(objectKey: string): string {
  if (driver() === "local") return objectKey;
  return `r2://${env().R2_BUCKET}/${objectKey}`;
}

/** Delete the uploaded object after a successful import (no retention). No-op for local. */
export async function deleteObject(objectKey: string): Promise<void> {
  if (driver() === "local") return;
  await r2Client().file(objectKey).delete();
}

/** Write `body` under `objectKey` — staging + full-grain exports for
 *  serp-semantics (both gzip'd bytes). local → plain file write (Bun.write
 *  creates intermediate directories, so tests need no setup); r2 → Bun's S3
 *  client, mirroring the read/delete primitives above. */
export async function putObject(
  objectKey: string,
  body: Uint8Array,
): Promise<void> {
  if (driver() === "local") {
    await Bun.write(objectKey, body);
    return;
  }
  await r2Client().file(objectKey).write(body);
}
