package appsec

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

	"github.com/akamai/AkamaiOPEN-edgegrid-golang/v12/pkg/appsec"
	"github.com/akamai/terraform-provider-akamai/v9/pkg/common/id"
	"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/customdiff"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)

func resourceMalwarePolicyActions() *schema.Resource {
	return &schema.Resource{
		CreateContext: resourceMalwarePolicyActionsCreate,
		ReadContext:   resourceMalwarePolicyActionsRead,
		UpdateContext: resourceMalwarePolicyActionsUpdate,
		DeleteContext: resourceMalwarePolicyActionsDelete,
		Importer: &schema.ResourceImporter{
			StateContext: schema.ImportStatePassthroughContext,
		},
		CustomizeDiff: customdiff.All(
			VerifyIDUnchanged,
		),
		Schema: map[string]*schema.Schema{
			"config_id": {
				Type:        schema.TypeInt,
				Required:    true,
				Description: "Unique identifier of the security configuration",
			},
			"security_policy_id": {
				Type:        schema.TypeString,
				Required:    true,
				Description: "Unique identifier of the security policy",
			},
			"malware_policy_actions": {
				Type:             schema.TypeString,
				Required:         true,
				ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsJSON),
				DiffSuppressFunc: suppressEquivalentJSONDiffsGeneric,
				Description:      "JSON-formatted list of malware policies and their associated actions",
			},
		},
	}
}

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

	configID, err := tf.GetIntValue("config_id", d)
	if err != nil {
		return diag.FromErr(err)
	}
	version, err := getModifiableConfigVersion(ctx, configID, "malwarePolicyActions", m)
	if err != nil {
		return diag.FromErr(err)
	}
	securityPolicyID, err := tf.GetStringValue("security_policy_id", d)
	if err != nil {
		return diag.FromErr(err)
	}
	jsonPostPayload, err := tf.GetStringValue("malware_policy_actions", d)
	if err != nil {
		return diag.FromErr(err)
	}
	jsonPayloadRaw := []byte(jsonPostPayload)

	_, err = client.UpdateMalwarePolicyActions(ctx, appsec.UpdateMalwarePolicyActionsRequest{
		ConfigID:             configID,
		Version:              version,
		PolicyID:             securityPolicyID,
		MalwarePolicyActions: jsonPayloadRaw,
	})
	if err != nil {
		logger.Errorf("calling 'updateMalwarePolicyActions': %s", err.Error())
		return diag.FromErr(err)
	}

	d.SetId(fmt.Sprintf("%d:%s", configID, securityPolicyID))

	return resourceMalwarePolicyActionsRead(ctx, d, m)
}

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

	iDParts, err := id.Split(d.Id(), 2, "configID:securityPolicyID")
	if err != nil {
		return diag.FromErr(err)
	}

	configID, err := strconv.Atoi(iDParts[0])
	if err != nil {
		return diag.FromErr(err)
	}
	version, err := getLatestConfigVersion(ctx, configID, m)
	if err != nil {
		return diag.FromErr(err)
	}
	securityPolicyID := iDParts[1]

	malwarePolicyActions, err := client.GetMalwarePolicyActions(ctx, appsec.GetMalwarePolicyActionsRequest{
		ConfigID: configID,
		Version:  version,
		PolicyID: securityPolicyID,
	})
	if err != nil {
		logger.Errorf("calling 'getMalwarePolicyActions': %s", err.Error())
		return diag.FromErr(err)
	}

	if err := d.Set("config_id", configID); err != nil {
		return diag.Errorf("%s: %s", tf.ErrValueSet, err.Error())
	}
	if err := d.Set("security_policy_id", securityPolicyID); err != nil {
		return diag.Errorf("%s: %s", tf.ErrValueSet, err.Error())
	}
	jsonBody, err := json.Marshal(malwarePolicyActions)
	if err != nil {
		return diag.FromErr(err)
	}
	if err := d.Set("malware_policy_actions", string(jsonBody)); err != nil {
		return diag.Errorf("%s: %s", tf.ErrValueSet, err.Error())
	}

	return nil
}

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

	iDParts, err := id.Split(d.Id(), 2, "configID:securityPolicyID")
	if err != nil {
		return diag.FromErr(err)
	}
	configID, err := strconv.Atoi(iDParts[0])
	if err != nil {
		return diag.FromErr(err)
	}
	version, err := getModifiableConfigVersion(ctx, configID, "malwarePolicyActions", m)
	if err != nil {
		return diag.FromErr(err)
	}
	securityPolicyID := iDParts[1]
	jsonPostPayload, err := tf.GetStringValue("malware_policy_actions", d)
	if err != nil {
		return diag.FromErr(err)
	}
	jsonPayloadRaw := []byte(jsonPostPayload)

	_, err = client.UpdateMalwarePolicyActions(ctx, appsec.UpdateMalwarePolicyActionsRequest{
		ConfigID:             configID,
		Version:              version,
		PolicyID:             securityPolicyID,
		MalwarePolicyActions: jsonPayloadRaw,
	})
	if err != nil {
		logger.Errorf("calling 'updateMalwarePolicyActions': %s", err.Error())
		return diag.FromErr(err)
	}

	d.SetId(fmt.Sprintf("%d:%s", configID, securityPolicyID))

	return resourceMalwarePolicyActionsRead(ctx, d, m)
}

func resourceMalwarePolicyActionsDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	return schema.NoopContext(ctx, d, m)
}
