package httptransport

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/quay/claircore"

	"github.com/quay/clair/v4/indexer"
	"github.com/quay/clair/v4/matcher"
)

func TestInitialized(t *testing.T) {
	var initd bool
	digest := claircore.MustParseDigest("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
	h := &VulnerabilityReportHandler{
		Matcher: &matcher.Mock{
			Initialized_: func(_ context.Context) (bool, error) {
				return initd, nil
			},
		},
		Indexer: &indexer.Mock{
			IndexReport_: func(_ context.Context, d claircore.Digest) (*claircore.IndexReport, bool, error) {
				if got, want := d.String(), digest.String(); got != want {
					return nil, false, fmt.Errorf("unexpected digest: %v", got)
				}
				return nil, false, nil
			},
		},
	}
	srv := httptest.NewServer(h)
	defer srv.Close()
	c := srv.Client()

	res, err := c.Get(srv.URL + "/" + digest.String())
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()
	t.Log(res.Status)
	if res.StatusCode != http.StatusAccepted {
		t.Errorf("unexpected response")
	}

	initd = true
	res, err = c.Get(srv.URL + "/" + digest.String())
	if err != nil {
		t.Fatal(err)
	}
	defer res.Body.Close()
	t.Log(res.Status)
	if res.StatusCode != http.StatusNotFound {
		t.Errorf("unexpected response")
	}
}
