package workflow_builder

import (
	"oc-monitord/models"
	"strings"

	"cloud.o-forge.io/core/oc-lib/models/resources"
	"gopkg.in/yaml.v3"
)

func (b *ArgoBuilder) CreateService(id string, processing *resources.ProcessingResource) {
	new_service := models.Service{
		APIVersion: "v1",
		Kind:       "Service",
		Metadata: models.Metadata{
			Name: "workflow-service",
		},
		Spec: models.ServiceSpec{
			Selector: map[string]string{"app": "oc-service"},
			Ports:    []models.ServicePort{},
			Type:     "NodePort",
		},
	}
	if processing == nil {
		return
	}
	b.completeServicePorts(&new_service, id, processing)
	b.Services = append(b.Services, &new_service)
}

func (b *ArgoBuilder) completeServicePorts(service *models.Service, id string, processing *resources.ProcessingResource) {
	instance := processing.GetSelectedInstance()
	if instance != nil && instance.(*resources.ProcessingInstance).Access != nil && instance.(*resources.ProcessingInstance).Access.Container != nil {
		for _, execute := range instance.(*resources.ProcessingInstance).Access.Container.Exposes {
			if execute.PAT != 0 {
				new_port_translation := models.ServicePort{
					Name:       strings.ToLower(processing.Name) + id,
					Port:       execute.Port,
					TargetPort: execute.PAT,
					Protocol:   "TCP",
				}
				service.Spec.Ports = append(service.Spec.Ports, new_port_translation)
			}
		}
	}
}

func (b *ArgoBuilder) addServiceToArgo() error {
	for _, service := range b.Services {
		service_manifest, err := yaml.Marshal(service)
		if err != nil {
			return err
		}
		service_template := models.Template{Name: "workflow-service-pod",
			Resource: models.ServiceResource{
				Action:            "create",
				SuccessCondition:  "status.succeeded > 0",
				FailureCondition:  "status.failed > 3",
				SetOwnerReference: true,
				Manifest:          string(service_manifest),
			},
		}
		b.Workflow.Spec.Templates = append(b.Workflow.Spec.Templates, service_template)
	}
	return nil
}
