package builtin

import (
	"github.com/atlassian/smith/pkg/specchecker"
	"github.com/atlassian/smith/pkg/util"
	sc_v1b1 "github.com/kubernetes-sigs/service-catalog/pkg/apis/servicecatalog/v1beta1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime"
)

type serviceBinding struct {
}

func (serviceBinding) BeforeCreate(ctx *specchecker.Context, spec *unstructured.Unstructured) (runtime.Object /*updatedSpec*/, error) {
	return spec, nil
}

func (serviceBinding) ApplySpec(ctx *specchecker.Context, spec, actual *unstructured.Unstructured) (runtime.Object, error) {
	var sbSpec sc_v1b1.ServiceBinding
	if err := util.ConvertType(scV1B1Scheme, spec, &sbSpec); err != nil {
		return nil, err
	}
	var sbActual sc_v1b1.ServiceBinding
	if err := util.ConvertType(scV1B1Scheme, actual, &sbActual); err != nil {
		return nil, err
	}

	// managed by service catalog auth filtering just copy to make the comparison work
	sbSpec.Spec.UserInfo = sbActual.Spec.UserInfo

	err := setEmptyFieldsFromActual(&sbSpec.Spec, &sbActual.Spec,
		// users should never set these ref fields
		"InstanceRef",

		// users may set these fields, generally they are autogenerated
		"ExternalID",
	)
	if err != nil {
		return nil, err
	}

	return &sbSpec, nil
}
