#!/usr/bin/env bash
# 01_storage_roundtrip.sh — GOLAKE-010 + GOLAKE-011 + GOLAKE-012.
# PUT bytes → GET bytes-equal → LIST contains key → DELETE → GET 404.
# Uses a deterministic key under proof/<case_id>/ so concurrent runs
# don't collide and the bucket stays inspectable post-run.

set -uo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "${SCRIPT_DIR}/../lib/env.sh"
source "${SCRIPT_DIR}/../lib/http.sh"
source "${SCRIPT_DIR}/../lib/assert.sh"

CASE_ID="GOLAKE-010-012"
CASE_NAME="Storage round-trip — PUT → GET → LIST → DELETE → 404"
CASE_TYPE="integration"
if [ "${1:-}" = "--metadata-only" ]; then return 0 2>/dev/null || exit 0; fi

KEY="proof/${CASE_ID}/payload.bin"

# Deterministic 1 KiB payload — sha256 must round-trip.
PAYLOAD_FILE="${PROOF_REPORT_DIR}/raw/outputs/${CASE_ID}.payload"
mkdir -p "$(dirname "$PAYLOAD_FILE")"
seq 1 256 | awk '{printf "%04d-line\n", $1}' > "$PAYLOAD_FILE"
EXPECTED_SHA=$(sha256sum "$PAYLOAD_FILE" | awk '{print $1}')

# Idempotent prelude: clear any leftover from prior run.
proof_delete "$CASE_ID" "pre_clean" \
    "${PROOF_GATEWAY_URL}/v1/storage/delete/${KEY}" >/dev/null

# PUT.
proof_put "$CASE_ID" "put" \
    "${PROOF_GATEWAY_URL}/v1/storage/put/${KEY}" \
    "application/octet-stream" "@${PAYLOAD_FILE}" >/dev/null
proof_assert_status_in "$CASE_ID" "PUT → 200 or 201" "200 201" "put"

# GET — bytes must round-trip.
proof_get "$CASE_ID" "get" \
    "${PROOF_GATEWAY_URL}/v1/storage/get/${KEY}" >/dev/null
proof_assert_eq "$CASE_ID" "GET → 200" "200" \
    "$(proof_status_of "$CASE_ID" "get")"
ACTUAL_SHA=$(sha256sum \
    "${PROOF_REPORT_DIR}/raw/http/${CASE_ID}/get.body" | awk '{print $1}')
proof_assert_eq "$CASE_ID" "GET body sha256 matches PUT input" \
    "$EXPECTED_SHA" "$ACTUAL_SHA"

# LIST — must contain the key. /storage/list returns JSON array of keys.
proof_get "$CASE_ID" "list" \
    "${PROOF_GATEWAY_URL}/v1/storage/list" >/dev/null
proof_assert_eq "$CASE_ID" "LIST → 200" "200" \
    "$(proof_status_of "$CASE_ID" "list")"
list_body=$(proof_body_of "$CASE_ID" "list")
proof_assert_contains "$CASE_ID" "LIST contains the put key" "$KEY" "$list_body"

# DELETE.
proof_delete "$CASE_ID" "del" \
    "${PROOF_GATEWAY_URL}/v1/storage/delete/${KEY}" >/dev/null
proof_assert_status_in "$CASE_ID" "DELETE → 200 or 204" "200 204" "del"

# GET after DELETE → 404.
proof_get "$CASE_ID" "get_after_delete" \
    "${PROOF_GATEWAY_URL}/v1/storage/get/${KEY}" >/dev/null
proof_assert_eq "$CASE_ID" "GET after DELETE → 404" "404" \
    "$(proof_status_of "$CASE_ID" "get_after_delete")"
