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 resourceMalwarePolicy() *schema.Resource {
	return &schema.Resource{
		CreateContext: resourceMalwarePolicyCreate,
		ReadContext:   resourceMalwarePolicyRead,
		UpdateContext: resourceMalwarePolicyUpdate,
		DeleteContext: resourceMalwarePolicyDelete,
		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",
			},
			"malware_policy": {
				Type:             schema.TypeString,
				Required:         true,
				ValidateDiagFunc: validation.ToDiagFunc(validation.StringIsJSON),
				DiffSuppressFunc: suppressEquivalentMalwarePolicyJSONDiffs,
				Description:      "JSON-formatted definition of the malware policy",
			},
			"malware_policy_id": {
				Type:        schema.TypeInt,
				Computed:    true,
				Description: "Unique identifier of the malware policy",
			},
		},
	}
}

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

	configID, err := tf.GetIntValue("config_id", d)
	if err != nil {
		return diag.FromErr(err)
	}
	version, err := getModifiableConfigVersion(ctx, configID, "malwarePolicy", m)
	if err != nil {
		return diag.FromErr(err)
	}
	payload, err := tf.GetStringValue("malware_policy", d)
	if err != nil {
		return diag.FromErr(err)
	}
	payloadBytes := []byte(payload)
	policy := appsec.MalwarePolicyBody{}
	if err := json.Unmarshal(payloadBytes, &policy); err != nil {
		return diag.FromErr(err)
	}

	response, err := client.CreateMalwarePolicy(ctx, appsec.CreateMalwarePolicyRequest{
		ConfigID:      configID,
		ConfigVersion: version,
		Policy:        &policy,
	})
	if err != nil {
		logger.Warnf("calling 'createMalwarePolicy': %s", err.Error())
		return diag.FromErr(err)
	}

	d.SetId(fmt.Sprintf("%d:%d", configID, response.MalwarePolicyID))

	return resourceMalwarePolicyRead(ctx, d, meta)
}

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

	iDParts, err := id.Split(d.Id(), 2, "configID:malwarePolicyID")
	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)
	}
	malwarePolicyID, err := strconv.Atoi(iDParts[1])
	if err != nil {
		return diag.FromErr(err)
	}

	response, err := client.GetMalwarePolicy(ctx, appsec.GetMalwarePolicyRequest{
		ConfigID:        configID,
		ConfigVersion:   version,
		MalwarePolicyID: malwarePolicyID,
	})
	if err != nil {
		logger.Warnf("calling 'getMalwarePolicy': %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("malware_policy_id", malwarePolicyID); err != nil {
		return diag.Errorf("%s: %s", tf.ErrValueSet, err.Error())
	}
	jsonBody, err := json.Marshal(response)
	if err != nil {
		return diag.FromErr(err)
	}
	// Remove id from body of malware policy to avoid drift on re-apply.
	var i interface{}
	if err := json.Unmarshal(jsonBody, &i); err != nil {
		return diag.FromErr(err)
	}
	if m, ok := i.(map[string]interface{}); ok {
		delete(m, "id")
	}
	jsonBody, err = json.Marshal(i)
	if err != nil {
		return diag.FromErr(err)
	}
	if err := d.Set("malware_policy", string(jsonBody)); err != nil {
		return diag.Errorf("%s: %s", tf.ErrValueSet, err.Error())
	}

	return nil
}

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

	iDParts, err := id.Split(d.Id(), 2, "configID:malwarePolicyID")
	if err != nil {
		return diag.FromErr(err)
	}
	configID, err := strconv.Atoi(iDParts[0])
	if err != nil {
		return diag.FromErr(err)
	}
	malwarePolicyID, err := strconv.Atoi(iDParts[1])
	if err != nil {
		return diag.FromErr(err)
	}
	version, err := getModifiableConfigVersion(ctx, configID, "malwarePolicy", m)
	if err != nil {
		return diag.FromErr(err)
	}

	payload, err := tf.GetStringValue("malware_policy", d)
	if err != nil {
		return diag.FromErr(err)
	}
	payloadBytes := []byte(payload)
	policy := appsec.MalwarePolicyBody{}
	if err := json.Unmarshal(payloadBytes, &policy); err != nil {
		return diag.FromErr(err)
	}

	_, err = client.UpdateMalwarePolicy(ctx, appsec.UpdateMalwarePolicyRequest{
		ConfigID:        configID,
		ConfigVersion:   version,
		MalwarePolicyID: malwarePolicyID,
		Policy:          &policy,
	})
	if err != nil {
		logger.Warnf("calling 'updateMalwarePolicy': %s", err.Error())
		return diag.FromErr(err)
	}

	return resourceMalwarePolicyRead(ctx, d, meta)
}

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

	iDParts, err := id.Split(d.Id(), 2, "configID:malwarePolicyID")
	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, "malwarePolicy", m)
	if err != nil {
		return diag.FromErr(err)
	}
	malwarePolicyID, err := strconv.Atoi(iDParts[1])
	if err != nil {
		return diag.FromErr(err)
	}

	err = client.RemoveMalwarePolicy(ctx, appsec.RemoveMalwarePolicyRequest{
		ConfigID:        configID,
		ConfigVersion:   version,
		MalwarePolicyID: malwarePolicyID,
	})
	if err != nil {
		logger.Warnf("calling 'removeMalwarePolicy': %s", err.Error())
		return diag.FromErr(err)
	}
	return nil
}
