package client

import (
	"net/http"
	"testing"

	cerrdefs "github.com/containerd/errdefs"
	"github.com/moby/moby/api/types/container"
	"gotest.tools/v3/assert"
	is "gotest.tools/v3/assert/cmp"
)

func TestContainerPruneError(t *testing.T) {
	client, err := New(WithMockClient(errorMock(http.StatusInternalServerError, "Server error")))
	assert.NilError(t, err)

	_, err = client.ContainerPrune(t.Context(), ContainerPruneOptions{})
	assert.Check(t, is.ErrorType(err, cerrdefs.IsInternal))
}

func TestContainerPrune(t *testing.T) {
	const expectedURL = "/containers/prune"

	listCases := []struct {
		filters             Filters
		expectedQueryParams map[string]string
	}{
		{
			filters: Filters{},
			expectedQueryParams: map[string]string{
				"until":   "",
				"filter":  "",
				"filters": "",
			},
		},
		{
			filters: make(Filters).Add("dangling", "true"),
			expectedQueryParams: map[string]string{
				"until":   "",
				"filter":  "",
				"filters": `{"dangling":{"true":true}}`,
			},
		},
		{
			filters: make(Filters).
				Add("dangling", "true").
				Add("until", "2016-12-15T14:00"),
			expectedQueryParams: map[string]string{
				"until":   "",
				"filter":  "",
				"filters": `{"dangling":{"true":true},"until":{"2016-12-15T14:00":true}}`,
			},
		},
		{
			filters: make(Filters).Add("dangling", "false"),
			expectedQueryParams: map[string]string{
				"until":   "",
				"filter":  "",
				"filters": `{"dangling":{"false":true}}`,
			},
		},
		{
			filters: make(Filters).
				Add("dangling", "true").
				Add("label", "label1=foo").
				Add("label", "label2!=bar"),
			expectedQueryParams: map[string]string{
				"until":   "",
				"filter":  "",
				"filters": `{"dangling":{"true":true},"label":{"label1=foo":true,"label2!=bar":true}}`,
			},
		},
	}
	for _, listCase := range listCases {
		client, err := New(WithMockClient(func(req *http.Request) (*http.Response, error) {
			if err := assertRequest(req, http.MethodPost, expectedURL); err != nil {
				return nil, err
			}
			query := req.URL.Query()
			for key, expected := range listCase.expectedQueryParams {
				actual := query.Get(key)
				assert.Check(t, is.Equal(expected, actual))
			}
			return mockJSONResponse(http.StatusOK, nil, container.PruneReport{
				ContainersDeleted: []string{"container_id1", "container_id2"},
				SpaceReclaimed:    9999,
			})(req)
		}))
		assert.NilError(t, err)

		req, err := client.ContainerPrune(t.Context(), ContainerPruneOptions{Filters: listCase.filters})
		assert.NilError(t, err)
		assert.Check(t, is.Len(req.Report.ContainersDeleted, 2))
		assert.Check(t, is.Equal(uint64(9999), req.Report.SpaceReclaimed))
	}
}
