package orchestrator

import (
	"testing"

	"github.com/tech/sendico/payments/orchestrator/storage/model"
	orchestratorv1 "github.com/tech/sendico/pkg/proto/payments/orchestrator/v1"
)

func TestEndpointFromProtoCard(t *testing.T) {
	protoEndpoint := &orchestratorv1.PaymentEndpoint{
		Endpoint: &orchestratorv1.PaymentEndpoint_Card{
			Card: &orchestratorv1.CardEndpoint{
				Card:              &orchestratorv1.CardEndpoint_Pan{Pan: " 411111 "},
				CardholderName:    " Jane ",
				CardholderSurname: " Doe ",
				ExpMonth:          12,
				ExpYear:           2030,
				Country:           " US ",
				MaskedPan:         " ****1111 ",
			},
		},
		Metadata: map[string]string{"k": "v"},
	}

	modelEndpoint := endpointFromProto(protoEndpoint)
	if modelEndpoint.Type != model.EndpointTypeCard {
		t.Fatalf("expected card type, got %s", modelEndpoint.Type)
	}
	if modelEndpoint.Card == nil {
		t.Fatalf("card payload missing")
	}
	if modelEndpoint.Card.Pan != "411111" || modelEndpoint.Card.Cardholder != "Jane" || modelEndpoint.Card.CardholderSurname != "Doe" || modelEndpoint.Card.Country != "US" || modelEndpoint.Card.MaskedPan != "****1111" {
		t.Fatalf("card payload not trimmed as expected: %#v", modelEndpoint.Card)
	}
	if modelEndpoint.Metadata["k"] != "v" {
		t.Fatalf("metadata not preserved")
	}
}

func TestProtoEndpointFromModelCard(t *testing.T) {
	modelEndpoint := model.PaymentEndpoint{
		Type: model.EndpointTypeCard,
		Card: &model.CardEndpoint{
			Token:             "tok_123",
			Cardholder:        "Jane",
			CardholderSurname: "Doe",
			ExpMonth:          1,
			ExpYear:           2028,
			Country:           "GB",
			MaskedPan:         "****1234",
		},
		Metadata: map[string]string{"k": "v"},
	}

	protoEndpoint := protoEndpointFromModel(modelEndpoint)
	card := protoEndpoint.GetCard()
	if card == nil {
		t.Fatalf("card payload missing in proto")
	}
	token, ok := card.Card.(*orchestratorv1.CardEndpoint_Token)
	if !ok || token.Token != "tok_123" {
		t.Fatalf("expected token payload, got %T %#v", card.Card, card.Card)
	}
	if card.GetCardholderName() != "Jane" || card.GetCardholderSurname() != "Doe" || card.GetCountry() != "GB" || card.GetMaskedPan() != "****1234" {
		t.Fatalf("card details mismatch: %#v", card)
	}
	if protoEndpoint.GetMetadata()["k"] != "v" {
		t.Fatalf("metadata not preserved in proto endpoint")
	}
}
