import {HTTPException} from 'hono/http-exception'

// conflict branch of the idempotent client-minted-id create protocol: the
// insert's onConflictDoNothing came back empty, so the id either belongs to
// this caller's earlier create (a replay — return it) or to someone else
// (a forgery — reject, never leaking the existing row). a conflict without a
// client-sent id can only be a server-side id collision — same rejection
export const resolveClientIdReplay = async <T>(
  id: string | undefined,
  load: (id: string) => Promise<T | undefined>,
  isOwnReplay: (row: T) => boolean,
): Promise<T> => {
  const existing = id ? await load(id) : undefined
  if (!existing || !isOwnReplay(existing))
    throw new HTTPException(409, {message: 'id_taken'})
  return existing
}
