package appsec

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"strconv"

	"github.com/akamai/AkamaiOPEN-edgegrid-golang/v12/pkg/appsec"
	"github.com/akamai/terraform-provider-akamai/v9/pkg/common/tf"
	"github.com/akamai/terraform-provider-akamai/v9/pkg/meta"
	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func dataSourceMalwarePolicies() *schema.Resource {
	return &schema.Resource{
		ReadContext: dataSourceMalwarePoliciesRead,
		Schema: map[string]*schema.Schema{
			"config_id": {
				Type:        schema.TypeInt,
				Required:    true,
				Description: "Unique identifier of the security configuration",
			},
			"malware_policy_id": {
				Type:        schema.TypeInt,
				Optional:    true,
				Description: "Unique identifier of a specific malware policy for which to retrieve information",
			},
			"json": {
				Type:        schema.TypeString,
				Computed:    true,
				Description: "JSON representation",
			},
			"output_text": {
				Type:        schema.TypeString,
				Computed:    true,
				Description: "Text representation",
			},
		},
	}
}

func dataSourceMalwarePoliciesRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	meta := meta.Must(m)
	client := inst.Client(meta)
	logger := meta.Log("APPSEC", "dataSourceMalwarePoliciesRead")

	configID, err := tf.GetIntValue("config_id", d)
	if err != nil {
		return diag.FromErr(err)
	}
	version, err := getLatestConfigVersion(ctx, configID, m)
	if err != nil {
		return diag.FromErr(err)
	}
	malwarePolicyID, err := tf.GetIntValue("malware_policy_id", d)
	if err != nil && !errors.Is(err, tf.ErrNotFound) {
		return diag.FromErr(err)
	}

	ots := OutputTemplates{}
	InitTemplates(ots)
	var outputText string
	var jsonBody []byte
	if malwarePolicyID != 0 {
		malwarePolicy, err := client.GetMalwarePolicy(ctx, appsec.GetMalwarePolicyRequest{
			ConfigID:        configID,
			ConfigVersion:   version,
			MalwarePolicyID: malwarePolicyID})
		if err != nil {
			logger.Errorf("calling 'getMalwarePolicy': %s", err.Error())
			return diag.FromErr(err)
		}

		outputText, err = RenderTemplates(ots, "malwarePolicy", malwarePolicy)
		if err != nil {
			return diag.FromErr(err)
		}
		if err := d.Set("output_text", outputText); err != nil {
			return diag.Errorf("%s: %s", tf.ErrValueSet, err.Error())
		}
		jsonBody, err = json.Marshal(malwarePolicy)
		if err != nil {
			return diag.FromErr(err)
		}
	} else {
		malwarePolicies, err := client.GetMalwarePolicies(ctx, appsec.GetMalwarePoliciesRequest{
			ConfigID:        configID,
			ConfigVersion:   version,
			MalwarePolicyID: malwarePolicyID})
		if err != nil {
			logger.Errorf("calling 'getMalwarePolicies': %s", err.Error())
			return diag.FromErr(err)
		}

		ots := OutputTemplates{}
		InitTemplates(ots)
		outputText, err = RenderTemplates(ots, "malwarePolicies", malwarePolicies)
		if err != nil {
			return diag.FromErr(err)
		}
		jsonBody, err = json.Marshal(malwarePolicies)
		if err != nil {
			return diag.FromErr(err)
		}
	}
	if err := d.Set("output_text", outputText); err != nil {
		return diag.Errorf("%s: %s", tf.ErrValueSet, err.Error())
	}
	if err := d.Set("json", string(jsonBody)); err != nil {
		return diag.Errorf("%s: %s", tf.ErrValueSet, err.Error())
	}

	if malwarePolicyID == 0 {
		d.SetId(strconv.Itoa(configID))
	} else {
		d.SetId(fmt.Sprintf("%d:%d", configID, malwarePolicyID))
	}

	return nil
}
