/*
Copyright 2022 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package gcetasks

import (
	"fmt"

	compute "google.golang.org/api/compute/v1"
	"k8s.io/klog/v2"
	"k8s.io/kops/upup/pkg/fi"
	"k8s.io/kops/upup/pkg/fi/cloudup/gce"
	"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
	"k8s.io/kops/upup/pkg/fi/cloudup/terraformWriter"
)

// HTTPHealthcheck represents a GCE Healthcheck
// +kops:fitask
type HTTPHealthcheck struct {
	Name      *string
	Lifecycle fi.Lifecycle

	SelfLink    string
	Port        *int64
	RequestPath *string
}

var _ fi.CompareWithID = &HTTPHealthcheck{}

func (e *HTTPHealthcheck) CompareWithID() *string {
	return e.Name
}

func (e *HTTPHealthcheck) Find(c *fi.CloudupContext) (*HTTPHealthcheck, error) {
	cloud := c.T.Cloud.(gce.GCECloud)
	name := fi.ValueOf(e.Name)
	r, err := cloud.Compute().HTTPHealthChecks().Get(cloud.Project(), name)
	if err != nil {
		if gce.IsNotFound(err) {
			return nil, nil
		}
		return nil, fmt.Errorf("error getting HealthCheck %q: %v", name, err)
	}
	actual := &HTTPHealthcheck{
		Name:        fi.PtrTo(r.Name),
		Port:        fi.PtrTo(r.Port),
		RequestPath: fi.PtrTo(r.RequestPath),
		SelfLink:    r.SelfLink,
	}
	// System fields
	actual.Lifecycle = e.Lifecycle
	e.SelfLink = r.SelfLink
	return actual, nil
}

func (e *HTTPHealthcheck) Run(c *fi.CloudupContext) error {
	return fi.CloudupDefaultDeltaRunMethod(e, c)
}

func (_ *HTTPHealthcheck) CheckChanges(a, e, changes *HTTPHealthcheck) error {
	if fi.ValueOf(e.Name) == "" {
		return fi.RequiredField("Name")
	}
	return nil
}

func (h *HTTPHealthcheck) RenderGCE(t *gce.GCEAPITarget, a, e, changes *HTTPHealthcheck) error {
	if a == nil {
		o := &compute.HttpHealthCheck{
			Name:        fi.ValueOf(e.Name),
			Port:        fi.ValueOf(e.Port),
			RequestPath: fi.ValueOf(e.RequestPath),
		}

		klog.V(4).Infof("Creating Healthcheck %q", o.Name)
		r, err := t.Cloud.Compute().HTTPHealthChecks().Insert(t.Cloud.Project(), o)
		if err != nil {
			return fmt.Errorf("error creating Healthcheck %q: %v", o.Name, err)
		}
		if err := t.Cloud.WaitForOp(r); err != nil {
			return fmt.Errorf("error creating Healthcheck: %v", err)
		}
		h.SelfLink = r.TargetLink
	}
	return nil
}

type terraformHTTPHealthcheck struct {
	Name        string  `cty:"name"`
	Port        *int64  `cty:"port"`
	RequestPath *string `cty:"request_path"`
}

func (_ *HTTPHealthcheck) RenderTerraform(t *terraform.TerraformTarget, a, e, changes *HTTPHealthcheck) error {
	tf := &terraformHTTPHealthcheck{
		Name:        *e.Name,
		Port:        e.Port,
		RequestPath: e.RequestPath,
	}
	return t.RenderResource("google_compute_http_health_check", *e.Name, tf)
}

func (e *HTTPHealthcheck) TerraformLink() *terraformWriter.Literal {
	return terraformWriter.LiteralSelfLink("google_compute_http_health_check", *e.Name)
}
