// Copyright IBM Corp. 2014, 2026
// SPDX-License-Identifier: BUSL-1.1

package terraform

import (
	"testing"

	backendInit "github.com/hashicorp/terraform/internal/backend/init"
	"github.com/hashicorp/terraform/internal/providers"
	"github.com/zclconf/go-cty/cty"
	ctyjson "github.com/zclconf/go-cty/cty/json"
)

func init() {
	// Initialize the backends
	backendInit.Init(nil)
}

func TestMoveResourceState_DataStore(t *testing.T) {
	t.Parallel()

	nullResourceStateValue := cty.ObjectVal(map[string]cty.Value{
		"id": cty.StringVal("test"),
	})
	nullResourceStateJSON, err := ctyjson.Marshal(nullResourceStateValue, nullResourceStateValue.Type())

	if err != nil {
		t.Fatalf("failed to marshal null resource state: %s", err)
	}

	provider := &Provider{}
	req := providers.MoveResourceStateRequest{
		SourceProviderAddress: "registry.terraform.io/hashicorp/null",
		SourceStateJSON:       nullResourceStateJSON,
		SourceTypeName:        "null_resource",
		TargetTypeName:        "terraform_data",
	}
	resp := provider.MoveResourceState(req)

	if resp.Diagnostics.HasErrors() {
		t.Errorf("unexpected diagnostics: %s", resp.Diagnostics.Err())
	}

	expected, err := dataStoreResourceSchema().Body.CoerceValue(cty.EmptyObjectVal)
	if err != nil {
		t.Fatal(err)
	}
	expectedMap := expected.AsValueMap()

	expectedMap["id"] = cty.StringVal("test")
	expectedTargetState := cty.ObjectVal(expectedMap)

	if !resp.TargetState.RawEquals(expectedTargetState) {
		t.Errorf("expected state was:\n%#v\ngot state is:\n%#v\n", expectedTargetState, resp.TargetState)
	}
}

func TestMoveResourceState_NonExistentResource(t *testing.T) {
	t.Parallel()

	provider := &Provider{}
	req := providers.MoveResourceStateRequest{
		TargetTypeName: "nonexistent_resource",
	}
	resp := provider.MoveResourceState(req)

	if !resp.Diagnostics.HasErrors() {
		t.Fatal("expected diagnostics")
	}
}

func TestGetProviderSchema_ProviderConfigNotNil(t *testing.T) {
	provider := &Provider{}
	resp := provider.GetProviderSchema()

	if resp.Provider.Body == nil {
		t.Fatal("provider config schema body should not be nil; a nil body causes " +
			"a spurious ERROR-level log message in AttachSchemaTransformer")
	}
}
