package services

import (
	"testing"

	"github.com/google/uuid"
)

// TestDerivedMembershipListScan covers the sql.Scanner over a Postgres
// jsonb column — the wire format that ListDerivedMembers' jsonb_agg
// returns. Pinned because if a future migration changes the JSON shape
// (e.g. drops a key), the rendered Herkunft column on /projects/{id}
// silently breaks (t-paliad-143).
func TestDerivedMembershipListScan(t *testing.T) {
	unitA := uuid.New()
	unitB := uuid.New()

	cases := []struct {
		name string
		src  any
		want []DerivedMembership
	}{
		{
			name: "nil",
			src:  nil,
			want: nil,
		},
		{
			name: "single membership as bytes",
			src:  []byte(`[{"unit_id":"` + unitA.String() + `","unit_name":"Lehment","unit_role":"attorney"}]`),
			want: []DerivedMembership{{UnitID: unitA, UnitName: "Lehment", UnitRole: "attorney"}},
		},
		{
			name: "two memberships as string",
			src: `[
				{"unit_id":"` + unitA.String() + `","unit_name":"Lehment","unit_role":"attorney"},
				{"unit_id":"` + unitB.String() + `","unit_name":"Plassmann","unit_role":"pa"}
			]`,
			want: []DerivedMembership{
				{UnitID: unitA, UnitName: "Lehment", UnitRole: "attorney"},
				{UnitID: unitB, UnitName: "Plassmann", UnitRole: "pa"},
			},
		},
	}
	for _, tc := range cases {
		t.Run(tc.name, func(t *testing.T) {
			var got DerivedMembershipList
			if err := got.Scan(tc.src); err != nil {
				t.Fatalf("Scan: %v", err)
			}
			if len(got) != len(tc.want) {
				t.Fatalf("len: got %d want %d", len(got), len(tc.want))
			}
			for i := range got {
				if got[i] != tc.want[i] {
					t.Errorf("row %d: got %+v want %+v", i, got[i], tc.want[i])
				}
			}
		})
	}
}

// TestDerivedMembershipListScanRejectsUnknown ensures we don't silently
// accept random column types and produce an empty list (which would mask
// a schema regression).
func TestDerivedMembershipListScanRejectsUnknown(t *testing.T) {
	var l DerivedMembershipList
	if err := l.Scan(123); err == nil {
		t.Fatal("expected error scanning int into DerivedMembershipList, got nil")
	}
}
