import { env } from "../../../../env.js";
import { getLogger } from "../../../../logger.js";
import { del, get, put } from "@vercel/blob";

//#region src/domains/run/services/blob-storage/vercel-blob-provider.ts
const VERCEL_BLOB_TIMEOUT_MS = 3e4;
const logger = getLogger("VercelBlobStorageProvider");
var VercelBlobStorageProvider = class {
	token;
	constructor() {
		this.token = env.BLOB_READ_WRITE_TOKEN?.trim() || void 0;
		logger.info({}, "Initializing Vercel Blob storage provider");
	}
	async upload(params) {
		logger.debug({
			key: params.key,
			contentType: params.contentType
		}, "Uploading to Vercel Blob");
		try {
			const body = params.data instanceof Buffer ? params.data : Buffer.from(params.data);
			await put(params.key, body, {
				access: "private",
				contentType: params.contentType,
				token: this.token,
				addRandomSuffix: false,
				allowOverwrite: true,
				abortSignal: AbortSignal.timeout(VERCEL_BLOB_TIMEOUT_MS)
			});
		} catch (error) {
			logger.error({
				key: params.key,
				error
			}, "Vercel Blob upload failed");
			throw new Error(`Vercel Blob upload failed for key ${params.key}: ${error instanceof Error ? error.message : String(error)}`);
		}
	}
	async download(key) {
		logger.debug({ key }, "Downloading from Vercel Blob");
		try {
			const result = await get(key, {
				access: "private",
				token: this.token,
				abortSignal: AbortSignal.timeout(VERCEL_BLOB_TIMEOUT_MS)
			});
			if (result?.statusCode !== 200 || !result.stream) throw new Error(`Vercel Blob download failed for key ${key}: ${result?.statusCode ?? "no result"}`);
			return {
				data: new Uint8Array(await new Response(result.stream).arrayBuffer()),
				contentType: result.blob.contentType || "application/octet-stream"
			};
		} catch (error) {
			logger.error({
				key,
				error
			}, "Vercel Blob download failed");
			throw new Error(`Vercel Blob download failed for key ${key}: ${error instanceof Error ? error.message : String(error)}`);
		}
	}
	async delete(key) {
		logger.debug({ key }, "Deleting from Vercel Blob");
		try {
			await del(key, {
				token: this.token,
				abortSignal: AbortSignal.timeout(VERCEL_BLOB_TIMEOUT_MS)
			});
		} catch (error) {
			logger.error({
				key,
				error
			}, "Vercel Blob delete failed");
			throw new Error(`Vercel Blob delete failed for key ${key}: ${error instanceof Error ? error.message : String(error)}`);
		}
	}
};

//#endregion
export { VercelBlobStorageProvider };