package main

import (
	"bytes"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"testing"
)

func TestReadRecordsValidatesChecksumAndDeterministicID(t *testing.T) {
	data := json.RawMessage(`{"id":7,"name":"研发"}`)
	canonical, _ := json.Marshal(map[string]any{"source_system": "python-gateway", "entity_type": "departments", "legacy_id": "7", "data": data})
	digest := sha256.Sum256(canonical)
	line, _ := json.Marshal(record{SourceSystem: "python-gateway", EntityType: "departments", LegacyID: "7", Data: data, Checksum: hex.EncodeToString(digest[:])})
	items, source, counts, err := readRecords(bytes.NewReader(append(line, '\n')))
	if err != nil {
		t.Fatal(err)
	}
	if len(items) != 1 || items[0].NewID == "" || source == "" || counts["departments"] != 1 {
		t.Fatalf("unexpected result: %#v %s %#v", items, source, counts)
	}
	line[len(line)-2] ^= 1
	if _, _, _, err = readRecords(bytes.NewReader(append(line, '\n'))); err == nil {
		t.Fatal("expected tamper detection")
	}
}
