package sms_test

import (
	"context"
	"fmt"
	"testing"

	"gateway/internal/model/notification/provider/sms"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestChain_Send_FailoverToSecondProvider(t *testing.T) {
	primary := sms.NewMockSender(
		sms.WithMockName("mitake"),
		sms.WithMockSort(1),
		sms.WithMockError(fmt.Errorf("mitake down")),
	)
	backup := sms.NewMockSender(
		sms.WithMockName("twilio"),
		sms.WithMockSort(2),
		sms.WithMockMessageID("twilio-sid"),
	)

	chain := sms.NewChain(primary, backup)
	provider, id, err := chain.Send(context.Background(), &sms.Message{
		PhoneNumber:   "+886912345678",
		RecipientName: "User",
		Body:          "code 123456",
	})

	require.NoError(t, err)
	assert.Equal(t, "twilio", provider)
	assert.Equal(t, "twilio-sid", id)
	assert.Len(t, primary.Calls(), 1)
	assert.Len(t, backup.Calls(), 1)
}

func TestChain_Send_AllProvidersFail(t *testing.T) {
	chain := sms.NewChain(
		sms.ErrSender("a", 1, fmt.Errorf("a fail")),
		sms.ErrSender("b", 2, fmt.Errorf("b fail")),
	)
	_, _, err := chain.Send(context.Background(), &sms.Message{PhoneNumber: "+886900000000"})
	require.Error(t, err)
	assert.Contains(t, err.Error(), "all providers failed")
}
