package volume

import (
	"bytes"
	"encoding/hex"
	"testing"

	"Picocrypt-NG/internal/encoding"
)

// TestEncodeWithRSGolden pins the output of encodeWithRS — the production RS128
// payload encoder modified by the EncodeInto optimization — to a frozen byte
// vector. This guards the encode-side on-disk format end to end: chunk
// iteration order, the systematic RS128 data bytes, the always-pad-the-last-
// chunk rule for partial blocks (PKCS#7), and the parity bytes. A regression in
// any of those (e.g. a buffer-reuse bug in EncodeInto) is caught directly here,
// not only transitively via roundtrip self-consistency.
//
// The 200-byte input exercises the partial-block path: one full 128-byte chunk
// plus a padded final chunk (72 data bytes + 56 bytes of 0x38 PKCS#7 padding).
// Vector generated by the infectious FEC(128,136) codec — the same one the
// legacy Picocrypt .pcv format uses — so it freezes legacy encode compatibility.
func TestEncodeWithRSGolden(t *testing.T) {
	rs, err := encoding.NewRSCodecs()
	if err != nil {
		t.Fatalf("NewRSCodecs() failed: %v", err)
	}

	input := make([]byte, 200)
	for i := range input {
		input[i] = byte(i*7 + 1)
	}

	got, err := encodeWithRS(input, rs)
	if err != nil {
		t.Fatalf("encodeWithRS: %v", err)
	}

	// 200 bytes -> 1 full chunk + 1 padded chunk -> 2 * 136 = 272 bytes.
	// Layout: [chunk1 128 data | 8 parity][chunk2 72 data | 56*0x38 pad | 8 parity].
	const wantHex = "01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3da" +
		"e1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3ba" +
		"c1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939a" +
		"a1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a" +
		"a5d74e94add3b8cd81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b22" +
		"2930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb02" +
		"0910171e252c333a41484f565d646b7238383838383838383838383838383838" +
		"3838383838383838383838383838383838383838383838383838383838383838" +
		"38383838383838380fa400e1b30605bf"
	want, err := hex.DecodeString(wantHex)
	if err != nil {
		t.Fatalf("decode golden: %v", err)
	}

	if !bytes.Equal(got, want) {
		t.Errorf("encodeWithRS golden mismatch (encode format drift):\n got  %x\nwant %x", got, want)
	}
}
