package handler

import (
	"fmt"
	"strconv"
	"testing"

	junit "github.com/jstemmer/go-junit-report/formatter"
	"github.com/stretchr/testify/assert"

	"github.com/pingcap/test-infra/common/model"
	htest "github.com/pingcap/test-infra/services/tcms/tests/httptest"
)

func TestTriggerDailyTests(t *testing.T) {
	h := setup(t)
	defer h.Shutdown()

	_, body := htest.MustPOST[TriggerTestsResp](h.Echo, "/api/v1/dailyci/trigger")
	assert.NotZero(t, body.ID)
	assert.Equal(t, body.TriggeredCount, 2)
}

func TestGetTriggerStatusForDailyCI(t *testing.T) {
	h := setup(t)
	defer h.Shutdown()

	// a plan-exec that didn't finish
	_, exec := htest.MustGET[model.TestPlanExecution](h.Echo, "/api/v1/plan-executions/1")
	_, body := htest.MustGET[GetTriggerStatusForDailyCIResp](h.Echo, "/api/v1/dailyci/trigger/"+strconv.FormatInt(exec.CreatedAt.Time().Unix(), 10))
	assert.False(t, body.Finished)
}

func TestGetDailyCIReport(t *testing.T) {
	h := setup(t)
	defer h.Shutdown()

	_, exec := htest.MustGET[model.TestPlanExecution](h.Echo, "/api/v1/plan-executions/1")
	_, body := htest.MustGET[junit.JUnitTestSuites](h.Echo, fmt.Sprintf("/api/v1/dailyci?branch=main&id=%d&pretty", exec.CreatedAt.Time().Unix()))
	assert.Equal(t, 3, len(body.Suites))
}
