package appsec

import (
	"context"
	"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"
)

func resourceMalwarePolicyAction() *schema.Resource {
	return &schema.Resource{
		CreateContext: resourceMalwarePolicyActionCreate,
		ReadContext:   resourceMalwarePolicyActionRead,
		UpdateContext: resourceMalwarePolicyActionUpdate,
		DeleteContext: resourceMalwarePolicyActionDelete,
		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_id": {
				Type:        schema.TypeInt,
				Required:    true,
				Description: "Unique identifier of the malware policy",
			},
			"action": {
				Type:             schema.TypeString,
				Required:         true,
				ValidateDiagFunc: ValidateActions,
				Description:      "Action to be taken for requests scanned according to the malware policy",
			},
			"unscanned_action": {
				Type:             schema.TypeString,
				Required:         true,
				ValidateDiagFunc: ValidateActions,
				Description:      "Action to be taken for requests not scanned according to the malware policy",
			},
		},
	}
}

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

	configID, err := tf.GetIntValue("config_id", d)
	if err != nil {
		return diag.FromErr(err)
	}
	version, err := getModifiableConfigVersion(ctx, configID, "malwarePolicyAction", m)
	if err != nil {
		return diag.FromErr(err)
	}
	securityPolicyID, err := tf.GetStringValue("security_policy_id", d)
	if err != nil {
		return diag.FromErr(err)
	}
	malwarePolicyID, err := tf.GetIntValue("malware_policy_id", d)
	if err != nil {
		return diag.FromErr(err)
	}
	action, err := tf.GetStringValue("action", d)
	if err != nil {
		return diag.FromErr(err)
	}
	unscannedaction, err := tf.GetStringValue("unscanned_action", d)
	if err != nil {
		return diag.FromErr(err)
	}

	_, err = client.UpdateMalwarePolicyAction(ctx, appsec.UpdateMalwarePolicyActionRequest{
		ConfigID:        configID,
		Version:         version,
		PolicyID:        securityPolicyID,
		MalwarePolicyID: malwarePolicyID,
		Action:          action,
		UnscannedAction: unscannedaction,
	})
	if err != nil {
		logger.Errorf("calling 'updateMalwarePolicyAction': %s", err.Error())
		return diag.FromErr(err)
	}

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

	return resourceMalwarePolicyActionRead(ctx, d, m)
}

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

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

	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())
	}
	if err := d.Set("malware_policy_id", malwarePolicyID); err != nil {
		return diag.Errorf("%s: %s", tf.ErrValueSet, err.Error())
	}
	for _, action := range malwarepolicyactions.MalwarePolicyActions {
		if action.MalwarePolicyID == malwarePolicyID {
			if err := d.Set("action", action.Action); err != nil {
				return diag.Errorf("%s: %s", tf.ErrValueSet, err.Error())
			}
			if err := d.Set("unscanned_action", action.UnscannedAction); err != nil {
				return diag.Errorf("%s: %s", tf.ErrValueSet, err.Error())
			}
			break
		}
	}

	return nil
}

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

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

	_, err = client.UpdateMalwarePolicyAction(ctx, appsec.UpdateMalwarePolicyActionRequest{
		ConfigID:        configID,
		Version:         version,
		PolicyID:        securityPolicyID,
		MalwarePolicyID: malwarePolicyID,
		Action:          action,
		UnscannedAction: unscannedaction,
	})
	if err != nil {
		logger.Errorf("calling 'updateMalwarePolicyAction': %s", err.Error())
		return diag.FromErr(err)
	}

	return resourceMalwarePolicyActionRead(ctx, d, m)
}

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

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

	_, err = client.UpdateMalwarePolicyAction(ctx, appsec.UpdateMalwarePolicyActionRequest{
		ConfigID:        configID,
		Version:         version,
		PolicyID:        securityPolicyID,
		MalwarePolicyID: malwarePolicyID,
		Action:          "none",
		UnscannedAction: "none",
	})
	if err != nil {
		logger.Errorf("calling 'removeMalwarePolicyAction': %s", err.Error())
		return diag.FromErr(err)
	}
	return nil
}
