package integration_test

import (
	"encoding/json"
	"testing"

	"github.com/stretchr/testify/suite"

	v1 "github.com/AlchemyTelcoSolutions/callisto-so-bff/api/v1"
	"github.com/AlchemyTelcoSolutions/callisto-so-bff/integration_tests/expect"
	"github.com/AlchemyTelcoSolutions/callisto-so-bff/integration_tests/fakes"
	suiteclient "github.com/AlchemyTelcoSolutions/callisto-so-bff/integration_tests/suite-client"
)

type saleOrderUpdateSuite struct {
	suite.Suite
	ClientGenerator *suiteclient.ClientGenerator
}

func (s *saleOrderUpdateSuite) TestSaleOrderUpdate() {
	t := s.T()

	tests := []struct {
		name    string
		caseAPI string
		assert  func(t *testing.T, resp *v1.PostUpdateSaleOrdersRestResponse)
	}{
		{
			name:    "POST_SALE_NO_BFF_API_SUSCCESS_RESPONSE",
			caseAPI: fakes.NoBFFResponse,
			assert: func(t *testing.T, resp *v1.PostUpdateSaleOrdersRestResponse) {
				expect.ValidSaleOrderUpdateResponse(t, *resp, stringToMap(fakes.SOResponseUpdatePUTData))
			},
		},
		{
			name:    "POST_UPDATE_UNAUTHORIZED",
			caseAPI: fakes.ErrorUnauthorized,
			assert: func(t *testing.T, resp *v1.PostUpdateSaleOrdersRestResponse) {
				errorData := map[string]any{
					"code":    401.00,
					"message": "Unauthorized",
				}
				expectedData := map[string]any{
					"error":   errorData,
					"result":  nil,
					"success": false,
				}
				expect.ValidSaleOrderUpdateResponse(t, *resp, expectedData)
			},
		},
		{
			name:    "POST_UPDATE_INVALID_BFF",
			caseAPI: fakes.InvalidBFF,
			assert: func(t *testing.T, resp *v1.PostUpdateSaleOrdersRestResponse) {
				expect.ValidSaleOrderUpdateResponse(t, *resp, stringToMap(fakes.SOResponseUpdatePUTData))
			},
		},
		{
			name:    "POST_SALE_ORDER_UPDATE_HAPPY_PATH",
			caseAPI: fakes.Success,
			assert: func(t *testing.T, resp *v1.PostUpdateSaleOrdersRestResponse) {
				expect.ValidSaleOrderUpdateResponse(t, *resp, stringToMap(fakes.SOResponseUpdatePUTData))
			},
		},
		{
			name:    "POST_SALE_ORDER_UPDATE_NETSUITE_HAPPY_PATH",
			caseAPI: fakes.SuccessNetsuiteUpdate,
			assert: func(t *testing.T, resp *v1.PostUpdateSaleOrdersRestResponse) {
				expect.ValidSaleOrderUpdateResponse(t, *resp, stringToMap(fakes.SOResponseUpdatePUTData))
			},
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			cli := s.ClientGenerator.NewClient(t)
			resp := cli.PostSaleOrderLegacy(test.caseAPI)
			test.assert(t, resp)
		})
	}
}

func stringToMap(data string) map[string]any {
	result := map[string]interface{}{}
	if err := json.Unmarshal([]byte(data), &result); err != nil {
		panic(err)
	}
	return result
}
