import { a as assertUuid, c as DownloadNotFoundError, l as FulfillmentValidationError, s as ownerKeyOf } from "./types-Ao3zhbMU.js";
import { sql } from "drizzle-orm";
//#region src/digital/grant.ts
function firstRow$1(res) {
	return ((Array.isArray(res) ? res : res.rows) ?? [])[0];
}
function rowToAccessGrant(row) {
	const createdAt = row.created_at;
	return {
		id: String(row.id),
		orderId: String(row.order_id),
		itemId: String(row.item_id),
		ownerKey: String(row.owner_key),
		blobKey: String(row.blob_key),
		createdAt: createdAt instanceof Date ? createdAt : new Date(String(createdAt))
	};
}
async function grantDigitalAccess(tx, input) {
	assertUuid(input.orderId, "orderId");
	if (input.itemId.length === 0) throw new FulfillmentValidationError("itemId");
	if (!/^(user|email):./.test(input.ownerKey)) throw new FulfillmentValidationError("ownerKey");
	if (input.blobKey.length === 0) throw new FulfillmentValidationError("blobKey");
	const id = crypto.randomUUID();
	const inserted = firstRow$1(await tx.execute(sql`
    INSERT INTO access_grant (id, order_id, item_id, owner_key, blob_key)
    VALUES (
      ${id}::uuid,
      ${input.orderId}::uuid,
      ${input.itemId},
      ${input.ownerKey},
      ${input.blobKey}
    )
    ON CONFLICT (order_id, item_id, owner_key) DO NOTHING
    RETURNING id, order_id, item_id, owner_key, blob_key, created_at
  `));
	if (inserted) return rowToAccessGrant(inserted);
	const existing = firstRow$1(await tx.execute(sql`
    SELECT id, order_id, item_id, owner_key, blob_key, created_at
    FROM access_grant
    WHERE order_id = ${input.orderId}::uuid
      AND item_id = ${input.itemId}
      AND owner_key = ${input.ownerKey}
  `));
	if (!existing) throw new FulfillmentValidationError("grant");
	return rowToAccessGrant(existing);
}
//#endregion
//#region src/digital/token.ts
const DOWNLOAD_TTL_SECONDS = 3600;
function firstRow(res) {
	return ((Array.isArray(res) ? res : res.rows) ?? [])[0];
}
async function issueDownloadToken(q, grantId, requester, storage) {
	assertUuid(grantId, "grantId");
	const reqKey = ownerKeyOf(requester);
	const grant = firstRow(await q.execute(sql`
    SELECT owner_key, blob_key
    FROM access_grant
    WHERE id = ${grantId}::uuid
  `));
	if (!grant || String(grant.owner_key) !== reqKey) throw new DownloadNotFoundError(grantId);
	return storage.signedUrl(String(grant.blob_key), DOWNLOAD_TTL_SECONDS);
}
//#endregion
export { grantDigitalAccess as n, issueDownloadToken as t };
