package task

import (
	"context"
	"time"

	"github.com/tidbcloud/ticdc-service-ng/pkg/cloud"
	"github.com/tidbcloud/ticdc-service-ng/pkg/deploy"
	"github.com/tidbcloud/ticdc-service-ng/pkg/k8s"
	"k8s.io/apimachinery/pkg/types"
	"k8s.io/utils/ptr"
)

type volumeAttributesClass struct {
	*baseTask
}

func NewVolumeAttributesClassTask(ctx *Context) deploy.Task {
	return &volumeAttributesClass{
		baseTask: &baseTask{Context: ctx},
	}
}

func (t *volumeAttributesClass) Name() string {
	return "VolumeAttributesClass"
}

func (t *volumeAttributesClass) Create(ctx context.Context) deploy.Result {
	t.beginAt = ptr.To(time.Now())
	scType := t.Cdc.Spec.Storage.Type
	scIops := t.Cdc.Spec.Storage.Iops
	scThroughput := t.Cdc.Spec.Storage.ThroughputMbs
	name := types.NamespacedName{
		Name: t.getVolumeAttributesClassName(),
	}
	vac, err := t.CloudProvider.BuildVolumeAttributesClass(name, &cloud.VolumeAttributes{
		Type:          scType,
		Iops:          scIops,
		ThroughputMbs: scThroughput,
	})
	if err != nil {
		return deploy.Error(err)
	}
	if vac == nil {
		return deploy.Done()
	}
	err = k8s.Apply(ctx, t.Remote, vac)
	return deploy.PanicOrDone(err)
}

// Delete does nothing, because VolumeAttributesClass is shared by all cdc cluster in the same k8s cluster.
func (t *volumeAttributesClass) Delete(ctx context.Context) deploy.Result {
	return deploy.Done()
}
