package zoneredundantevicter

import (
	"context"

	"github.com/tidbcloud/aws-shared-provider/pkg/metrics"
	"github.com/tidbcloud/aws-shared-provider/pkg/types"
	"github.com/tidbcloud/aws-shared-provider/pkg/utils/labels"
	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/log"
)

func (r *Reconciler) evictPodPVC(ctx context.Context, pod *corev1.Pod) error {
	for i := range pod.Spec.Volumes {
		volume := &pod.Spec.Volumes[i]
		if volume.PersistentVolumeClaim == nil {
			continue
		}

		pvc := &corev1.PersistentVolumeClaim{}
		pvcName := volume.PersistentVolumeClaim.ClaimName
		if err := r.Client.Get(ctx, client.ObjectKey{Name: pvcName, Namespace: pod.Namespace}, pvc); err != nil {
			if apierrors.IsNotFound(err) {
				continue
			}
			return err
		}
		if pvc.DeletionTimestamp != nil {
			continue
		}
		if pvc.Annotations[types.AnnoVolumeSelectedNode] == "" {
			continue
		}
		if !pvcEvictable(pod) {
			metrics.ZRUnEvictablePVCCounter.WithLabelValues(
				pod.Labels[labels.ComponentLabelKey],
				pod.Name,
				pvcName,
				pod.Namespace).Inc()
			continue
		}
		if err := client.IgnoreNotFound(r.Client.Delete(ctx, pvc)); err != nil {
			return err
		}
		log.FromContext(ctx).Info("evict pod pvc", "pod", podName(pod), "pvc", pvc.Name)
		metrics.ZREvictPodPVCCounter.WithLabelValues(pod.Name, pvcName, pod.Namespace).Inc()
	}
	return nil
}
