package main

import (
	"encoding/json"
	"fmt"
	"strings"

	"github.com/Snowflake-Labs/terraform-provider-snowflake/pkg/resources"
)

const (
	testTemplate string = `package test

/*
 NOTE: automatically generated by scripts/snowflake_generate_grant_all.
			 Changes made directly to this file will be overwritten.
			 Make improvements there so everyone can benefit.
*/

import (
	"encoding/json"
	"testing"

	"github.com/chanzuckerberg/go-misc/tftest"
	"github.com/gruntwork-io/terratest/modules/terraform"
)

const vars string = %q

func TestModule(t *testing.T) {
	test := tftest.Test{
		// just run init, swtich to Plan or Apply when you can
		Mode: tftest.Init,

		Setup: func(t *testing.T) *terraform.Options {
			opts := tftest.Options(
				tftest.DefaultRegion,
				mustJson(vars),
			)
			opts.TerraformDir = "."

			return opts
		},
		Validate: func(t *testing.T, options *terraform.Options) {},
	}

	test.Run(t)
}

func mustJson(jsonData string) map[string]interface{} {
	unmarshalled := map[string]interface{}{}

	err := json.Unmarshal([]byte(jsonData), &unmarshalled)
	if err != nil {
		panic(err) // should never happen since generated code
	}
	return unmarshalled
}
`
)

// generateVars currently generates vars for a basic integration test
// many input variable combinations are currently missing
func generateTestVars(grant *resources.TerraformGrantResource) map[string]interface{} {
	vars := map[string]interface{}{}

	for name := range grant.Resource.Schema {
		if strings.HasSuffix(name, "_name") {
			vars[name] = strings.TrimSuffix(name, "_name")
			continue
		}

		if name == "roles" {
			vars[name] = []string{"role_a", "role_b", "role_c"}
			continue
		}

		if name == "shares" {
			vars[name] = []string{"share_a", "share_b", "share_c"}
			continue
		}
	}

	return vars
}

func generateTest(grant *resources.TerraformGrantResource) (string, error) {
	vars := generateTestVars(grant)
	data, err := json.Marshal(vars)
	if err != nil {
		return "", err
	}

	return fmt.Sprintf(testTemplate, string(data)), nil
}
