package hypervisors

import (
	"context"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/sdn/hypervisors"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
)

func resourceHypervisorCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	return diag.Errorf(
		"It's impossible to create a hypervisor from terraform")
}

func resourceHypervisorRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	hypervisor, err := utilityHypervisorCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	flattenHypervisorResource(d, hypervisor)
	d.SetId(hypervisor.Name)

	return nil
}

func resourceHypervisorUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	c := m.(*controller.ControllerCfg)
	req := hypervisors.UpdateDisplayNameRequest{
		Name:        d.Get("name").(string),
		DisplayName: d.Get("display_name").(string),
	}

	_, err := c.SDN().Hypervisors().UpdateDisplayName(ctx, req)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	return resourceHypervisorRead(ctx, d, m)
}

func resourceHypervisorDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	c := m.(*controller.ControllerCfg)

	req := hypervisors.DeleteRequest{
		Name: d.Get("name").(string),
	}

	_, err := c.SDN().Hypervisors().Delete(ctx, req)
	if err != nil {
		return diag.FromErr(err)
	}

	d.SetId("")

	return nil
}

func ResourceHypervisor() *schema.Resource {
	return &schema.Resource{
		SchemaVersion: 1,

		CreateContext: resourceHypervisorCreate,
		ReadContext:   resourceHypervisorRead,
		UpdateContext: resourceHypervisorUpdate,
		DeleteContext: resourceHypervisorDelete,

		Importer: &schema.ResourceImporter{
			StateContext: schema.ImportStatePassthroughContext,
		},

		Timeouts: &schema.ResourceTimeout{
			Create:  &constants.Timeout600s,
			Read:    &constants.Timeout300s,
			Update:  &constants.Timeout600s,
			Delete:  &constants.Timeout300s,
			Default: &constants.Timeout300s,
		},

		Schema: resourceHypervisorSchemaMake(),
	}
}
