package mxgateway

import (
	"os"
	"path/filepath"
	"testing"

	pb "gitea.dohertylan.com/dohertj2/mxaccessgw/clients/go/internal/generated"
	"google.golang.org/protobuf/encoding/protojson"
	"google.golang.org/protobuf/proto"
)

func TestGeneratedGoldenFixturesParse(t *testing.T) {
	tests := []struct {
		name string
		path string
		msg  proto.Message
	}{
		{
			name: "open session reply",
			path: filepath.Join("..", "..", "proto", "fixtures", "golden", "open-session-reply.ok.json"),
			msg:  &pb.OpenSessionReply{},
		},
		{
			name: "register command request",
			path: filepath.Join("..", "..", "proto", "fixtures", "golden", "register-command-request.json"),
			msg:  &pb.MxCommandRequest{},
		},
		{
			name: "on data change event",
			path: filepath.Join("..", "..", "proto", "fixtures", "golden", "on-data-change-event.json"),
			msg:  &pb.MxEvent{},
		},
	}

	unmarshal := protojson.UnmarshalOptions{DiscardUnknown: false}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			data, err := os.ReadFile(tt.path)
			if err != nil {
				t.Fatalf("read fixture: %v", err)
			}

			if err := unmarshal.Unmarshal(data, tt.msg); err != nil {
				t.Fatalf("parse fixture: %v", err)
			}
		})
	}
}

func TestOpenSessionFixtureProtocolVersions(t *testing.T) {
	data, err := os.ReadFile(filepath.Join("..", "..", "proto", "fixtures", "golden", "open-session-reply.ok.json"))
	if err != nil {
		t.Fatalf("read fixture: %v", err)
	}

	var reply pb.OpenSessionReply
	if err := protojson.Unmarshal(data, &reply); err != nil {
		t.Fatalf("parse fixture: %v", err)
	}

	if reply.GetGatewayProtocolVersion() != GatewayProtocolVersion {
		t.Fatalf("gateway protocol = %d, want %d", reply.GetGatewayProtocolVersion(), GatewayProtocolVersion)
	}

	if reply.GetWorkerProtocolVersion() != WorkerProtocolVersion {
		t.Fatalf("worker protocol = %d, want %d", reply.GetWorkerProtocolVersion(), WorkerProtocolVersion)
	}
}
