package platform

import (
	"bytes"
	"context"
	"encoding/json"
	"testing"

	"github.com/DATA-DOG/go-sqlmock"
)

func TestProductionVehicleSourcePolicyUsesStableEmptyAuditArray(t *testing.T) {
	db, mock, err := sqlmock.New()
	if err != nil {
		t.Fatal(err)
	}
	defer db.Close()
	store := NewProductionStore(db, nil, "")
	mock.ExpectQuery(`SELECT version, updated_by`).WithArgs("VIN001").
		WillReturnRows(sqlmock.NewRows([]string{"version", "updated_by", "updated_at"}))
	mock.ExpectQuery(`SELECT version, protocol, source_ref`).WithArgs("VIN001").
		WillReturnRows(sqlmock.NewRows([]string{"version", "protocol", "source_ref", "source_label", "actor", "changed_at", "summary"}))
	config, err := store.VehicleSourcePolicy(context.Background(), "VIN001")
	if err != nil {
		t.Fatal(err)
	}
	if config.Audit == nil || len(config.Audit) != 0 {
		t.Fatalf("empty audit must be a stable slice: %#v", config.Audit)
	}
	encoded, err := json.Marshal(config)
	if err != nil {
		t.Fatal(err)
	}
	if string(encoded) == "" || !json.Valid(encoded) {
		t.Fatalf("policy JSON is invalid: %s", encoded)
	}
	if !bytes.Contains(encoded, []byte(`"audit":[]`)) {
		t.Fatalf("empty audit encoded as null: %s", encoded)
	}
	if err := mock.ExpectationsWereMet(); err != nil {
		t.Fatal(err)
	}
}
