// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package synapse

import (
	"fmt"
	"log"
	"time"

	"github.com/Azure/azure-sdk-for-go/services/preview/synapse/mgmt/v2.0/synapse" // nolint: staticcheck
	"github.com/hashicorp/terraform-provider-azurerm/internal/clients"
	"github.com/hashicorp/terraform-provider-azurerm/internal/features"
	"github.com/hashicorp/terraform-provider-azurerm/internal/services/synapse/parse"
	"github.com/hashicorp/terraform-provider-azurerm/internal/services/synapse/validate"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk"
	"github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation"
	"github.com/hashicorp/terraform-provider-azurerm/internal/timeouts"
	"github.com/hashicorp/terraform-provider-azurerm/utils"
)

func resourceSynapseSqlPoolVulnerabilityAssessment() *pluginsdk.Resource {
	return &pluginsdk.Resource{
		Create: resourceSynapseSqlPoolVulnerabilityAssessmentCreateUpdate,
		Read:   resourceSynapseSqlPoolVulnerabilityAssessmentRead,
		Update: resourceSynapseSqlPoolVulnerabilityAssessmentCreateUpdate,
		Delete: resourceSynapseSqlPoolVulnerabilityAssessmentDelete,

		Timeouts: &pluginsdk.ResourceTimeout{
			Create: pluginsdk.DefaultTimeout(30 * time.Minute),
			Read:   pluginsdk.DefaultTimeout(5 * time.Minute),
			Update: pluginsdk.DefaultTimeout(30 * time.Minute),
			Delete: pluginsdk.DefaultTimeout(30 * time.Minute),
		},

		Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error {
			_, err := parse.SqlPoolVulnerabilityAssessmentID(id)
			return err
		}),

		Schema: map[string]*pluginsdk.Schema{
			"sql_pool_security_alert_policy_id": {
				Type:         pluginsdk.TypeString,
				Required:     true,
				ForceNew:     true,
				ValidateFunc: validate.SqlPoolSecurityAlertPolicyID,
			},

			"storage_container_path": {
				Type:         pluginsdk.TypeString,
				Required:     true,
				ValidateFunc: validation.StringIsNotEmpty,
			},

			"recurring_scans": {
				Type:     pluginsdk.TypeList,
				Optional: true,
				// NOTE: O+C API returns defaults for these even if omitted so this needs to remain
				Computed: true,
				MaxItems: 1,
				Elem: &pluginsdk.Resource{
					Schema: map[string]*pluginsdk.Schema{
						"email_subscription_admins_enabled": {
							Type:     pluginsdk.TypeBool,
							Optional: true,
							// API actually defaults this to true
							Default: features.FourPointOhBeta(),
						},

						"emails": {
							Type:     pluginsdk.TypeList,
							Optional: true,
							Elem: &pluginsdk.Schema{
								Type:         pluginsdk.TypeString,
								ValidateFunc: validation.StringIsNotEmpty,
							},
						},

						"enabled": {
							Type:     pluginsdk.TypeBool,
							Optional: true,
							Default:  false,
						},
					},
				},
			},

			"storage_account_access_key": {
				Type:         pluginsdk.TypeString,
				Optional:     true,
				Sensitive:    true,
				ValidateFunc: validation.StringIsNotEmpty,
			},

			"storage_container_sas_key": {
				Type:         pluginsdk.TypeString,
				Optional:     true,
				Sensitive:    true,
				ValidateFunc: validation.StringIsNotEmpty,
			},
		},
	}
}

func resourceSynapseSqlPoolVulnerabilityAssessmentCreateUpdate(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).Synapse.SqlPoolVulnerabilityAssessmentsClient
	ctx, cancel := timeouts.ForCreateUpdate(meta.(*clients.Client).StopContext, d)
	defer cancel()

	policyId, err := parse.SqlPoolSecurityAlertPolicyID(d.Get("sql_pool_security_alert_policy_id").(string))
	if err != nil {
		return err
	}

	policyClient := meta.(*clients.Client).Synapse.SqlPoolSecurityAlertPolicyClient
	policy, err := policyClient.Get(ctx, policyId.ResourceGroup, policyId.WorkspaceName, policyId.SqlPoolName)
	if err != nil {
		return fmt.Errorf("retrieving %s: %+v", policyId, err)
	}

	id := parse.NewSqlPoolVulnerabilityAssessmentID(policyId.SubscriptionId, policyId.ResourceGroup, policyId.WorkspaceName, policyId.SqlPoolName, "default")

	if policy.State != synapse.SecurityAlertPolicyStateEnabled {
		return fmt.Errorf("updating %s: security alert policy is not enabled", id)
	}

	vulnerabilityAssessment := expandSqlPoolVulnerabilityAssessment(d)

	_, err = client.CreateOrUpdate(ctx, policyId.ResourceGroup, policyId.WorkspaceName, policyId.SqlPoolName, *vulnerabilityAssessment)
	if err != nil {
		return fmt.Errorf("updating %s: %+v", id, err)
	}

	d.SetId(id.ID())

	return resourceSynapseSqlPoolVulnerabilityAssessmentRead(d, meta)
}

func resourceSynapseSqlPoolVulnerabilityAssessmentRead(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).Synapse.SqlPoolVulnerabilityAssessmentsClient
	ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d)
	defer cancel()

	id, err := parse.SqlPoolVulnerabilityAssessmentID(d.Id())
	if err != nil {
		return err
	}

	resp, err := client.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.SqlPoolName)
	if err != nil {
		if utils.ResponseWasNotFound(resp.Response) {
			log.Printf("[INFO] synapse %s does not exist - removing from state", id)
			d.SetId("")
			return nil
		}

		return fmt.Errorf("retrieving %s: %+v", id, err)
	}

	policyClient := meta.(*clients.Client).Synapse.SqlPoolSecurityAlertPolicyClient
	policy, err := policyClient.Get(ctx, id.ResourceGroup, id.WorkspaceName, id.SqlPoolName)
	if err != nil {
		return fmt.Errorf("retrieving security alert policy for %s: %+v", id, err)
	}
	d.Set("sql_pool_security_alert_policy_id", policy.ID)

	if props := resp.SQLPoolVulnerabilityAssessmentProperties; props != nil {
		d.Set("storage_container_path", props.StorageContainerPath)

		if v, ok := d.GetOk("storage_account_access_key"); ok {
			d.Set("storage_account_access_key", v)
		}

		if v, ok := d.GetOk("storage_container_sas_key"); ok {
			d.Set("storage_container_sas_key", v)
		}

		if props.RecurringScans != nil {
			d.Set("recurring_scans", flattenRecurringScans(props.RecurringScans))
		}
	}
	return nil
}

func resourceSynapseSqlPoolVulnerabilityAssessmentDelete(d *pluginsdk.ResourceData, meta interface{}) error {
	client := meta.(*clients.Client).Synapse.SqlPoolVulnerabilityAssessmentsClient
	ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d)
	defer cancel()

	id, err := parse.SqlPoolVulnerabilityAssessmentID(d.Id())
	if err != nil {
		return err
	}

	if _, err = client.Delete(ctx, id.ResourceGroup, id.WorkspaceName, id.SqlPoolName); err != nil {
		return fmt.Errorf("deleting %s: %+v", id, err)
	}

	return nil
}

func expandSqlPoolVulnerabilityAssessment(d *pluginsdk.ResourceData) *synapse.SQLPoolVulnerabilityAssessment {
	storageContainerPath := d.Get("storage_container_path").(string)

	vulnerabilityAssessment := synapse.SQLPoolVulnerabilityAssessment{
		SQLPoolVulnerabilityAssessmentProperties: &synapse.SQLPoolVulnerabilityAssessmentProperties{
			StorageContainerPath: &storageContainerPath,
		},
	}

	props := vulnerabilityAssessment.SQLPoolVulnerabilityAssessmentProperties

	if v, ok := d.GetOk("storage_account_access_key"); ok {
		props.StorageAccountAccessKey = utils.String(v.(string))
	}

	if v, ok := d.GetOk("storage_container_sas_key"); ok {
		props.StorageContainerSasKey = utils.String(v.(string))
	}

	if _, ok := d.GetOk("recurring_scans"); ok {
		props.RecurringScans = expandRecurringScans(d)
	}

	return &vulnerabilityAssessment
}
