package task

import (
	"context"
	"encoding/json"
	"testing"

	maintent "github.com/tidbcloud/devops/entity/maintenance"
	cmxapi "github.com/tidbcloud/devops/pkg/service/clustermaintenance/api"
	"go.uber.org/mock/gomock"
)

func TestHandleMaintenanceAnnotationRequest(t *testing.T) {
	ctrl := gomock.NewController(t)
	defer ctrl.Finish()

	mockAPI := cmxapi.NewMockServiceAPI(ctrl)
	s := &svc{maintenanceWindowSvc: mockAPI}

	ann := maintenanceAnnotation{}
	ann.Spec.ClusterID = "42"
	raw, err := json.Marshal(ann)
	if err != nil {
		t.Fatal(err)
	}

	mw := &maintent.ClusterMaintenance{
		ClusterMaintenanceInRepo: maintent.ClusterMaintenanceInRepo{ID: 1},
		Task: maintent.ClusterMaintenanceTask{
			Executions: []maintent.ClusterMaintenanceExecution{
				{ID: 7, ClusterID: 42, Status: maintent.ClusterMaintenanceExecutionStatusPending},
			},
		},
	}

	mockAPI.EXPECT().StartMaintenanceExecution(gomock.Any(), uint64(1), uint64(7)).Return(nil)

	annotations := map[string]string{
		annotationRequestStepPrefix + "3": string(raw),
	}
	changed, err := s.handleMaintenanceAnnotation(context.Background(), annotationRequestStepPrefix+"3", string(raw), mw, annotations)
	if err != nil {
		t.Fatalf("handleMaintenanceAnnotation() error = %v", err)
	}
	if !changed {
		t.Fatal("expected annotation to be updated")
	}

	var updated maintenanceAnnotation
	if err := json.Unmarshal([]byte(annotations[annotationRequestStepPrefix+"3"]), &updated); err != nil {
		t.Fatal(err)
	}
	if updated.Status.Result != maintenanceAnnotationDone {
		t.Fatalf("status.result = %q, want %q", updated.Status.Result, maintenanceAnnotationDone)
	}
}
