package kvmvm

import (
	"context"
	"fmt"
	"strings"

	log "github.com/sirupsen/logrus"
)

func resourceCompueteStateUpgradeV1(ctx context.Context, rawState map[string]interface{}, meta any) (map[string]interface{}, error) {
	log.Debug("resourceCompueteStateUpgradeV1: upgrading state")
	customFields, ok := rawState["custom_fields"]
	if !ok || customFields == nil {
		rawState["custom_fields"] = "{}"
		return rawState, nil
	}

	b := &strings.Builder{}
	b.WriteString("{")
	oldCustomFieldsSlice := customFields.([]interface{})
	for i := range oldCustomFieldsSlice {
		oldCustomFields := oldCustomFieldsSlice[i].(map[string]interface{})
		b.WriteString(fmt.Sprintf(`"%s":"%s"`, oldCustomFields["key"], oldCustomFields["val"]))
		if i < len(oldCustomFieldsSlice)-1 {
			b.WriteString(",")
		}
	}
	b.WriteString("}")
	rawState["custom_fields"] = b.String()

	return rawState, nil
}

func resourceComputeStateUpgradeV2(ctx context.Context, rawState map[string]interface{}, meta any) (map[string]interface{}, error) {
	log.Debug("resourceComputeStateUpgradeV2: upgrading state")
	
	delete(rawState, "with_default_vins")

	return rawState, nil
}
