package handlers_test

import (
	"context"
	"github.com/fiskerinc/cloud-services/pkg/clickhouse"
	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/julienschmidt/httprouter"
	"github.com/stretchr/testify/assert"
	"net/http"
	"net/http/httptest"
	"otaupdate/handlers"
	"otaupdate/services"
	"testing"
)

func TestHandleVINECUStatsGetList(t *testing.T) {
	validQuery := "?min_out_of_range_pct=10&min_zero_pct=0.009&hours=160&ecus=ADAS&ecus=ICC&ecus=TREX"
	validVin := "TREXTEST7TUR9NXGC"
	validDBC := "73583d63735b404f5209a71107c3d2174b0ab1ba40bd826b8cb69668598b0395"
	tests := map[string]struct {
		q         string
		conn      clickhouse.ConnInterface
		expStatus int
		expBody   string
	}{
		"correct": {
			q: validQuery,
			conn: &clickhouse.MockConn{ExpectedResult: []common.ECUStat{
				{
					ECUName:          "ADAS",
					IncorrectValues:  1,
					AllZero:          1,
					ECUSignalsTotal:  231,
					SignalsTotal:     2221,
					IncorrectPercent: 0.04,
					ZeroPercent:      0.003,
				},
				{
					ECUName:          "TREX",
					IncorrectValues:  0,
					AllZero:          0,
					ECUSignalsTotal:  77,
					SignalsTotal:     9789,
					IncorrectPercent: 0.55,
					ZeroPercent:      0.36,
				},
			}},
			expStatus: http.StatusOK,
			expBody:   `{"data":[{"ecu_name":"ADAS","signals_w_incorrect_values":1,"signals_all_zero":1,"number_of_ecu_signals":231,"total_signal_records":2221,"incorrect_val_signal_pct":0.04,"zero_signals_pct":0.003},{"ecu_name":"TREX","signals_w_incorrect_values":0,"signals_all_zero":0,"number_of_ecu_signals":77,"total_signal_records":9789,"incorrect_val_signal_pct":0.55,"zero_signals_pct":0.36}]}`,
		},
		"failed_filter": {
			q:         "",
			expStatus: http.StatusBadRequest,
			expBody:   `{"message":"MinOutOfRangePct required. MinZeroPct required. Hours required. ECUs required","error":"Bad Request"}`,
		},
		"failed_query": {
			q:         validQuery,
			conn:      &clickhouse.MockConn{ExpectedResult: someErr},
			expStatus: http.StatusServiceUnavailable,
			expBody:   `{"message":"json: cannot unmarshal object into Go value of type []common.ECUStat","error":"Service Unavailable"}`,
		},
	}

	for tname, tt := range tests {
		t.Run(tname, func(t *testing.T) {
			services.SetClickhouseConn(tt.conn)
			w := httptest.NewRecorder()

			p := httprouter.Params{
				{Key: "vin", Value: validVin},
				{Key: "dbc", Value: validDBC},
			}
			ctx := context.WithValue(context.Background(), httprouter.ParamsKey, p)
			r := httptest.NewRequest(http.MethodGet, "http://example.com/ecu_stats/vin/dbc"+tt.q, nil).
				WithContext(ctx)

			handlers.HandleVINECUStatsGetList(w, r)
			assert.Equal(t, tt.expStatus, w.Code)
			assert.Equal(t, tt.expBody, w.Body.String())
		})
	}
}
