package objectstorage

import (
	"context"
	"log"
	"time"

	"github.com/civo/civogo"
	"github.com/civo/terraform-provider-civo/internal/utils"
	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

// ResourceObjectStoreCredential function returns a schema.Resource that represents an Object Store Credential.
// This can be used to create, read, update, and delete operations for an Object Store Credential in the infrastructure.
func ResourceObjectStoreCredential() *schema.Resource {
	return &schema.Resource{
		Description: "Provides an Object Store Credential resource. This can be used to create, modify, and delete object stores credential.",
		Schema: map[string]*schema.Schema{
			"name": {
				Type:         schema.TypeString,
				Required:     true,
				ValidateFunc: utils.ValidateNameSize,
				Description:  "The name of the Object Store Credential. Must be unique.",
			},
			"region": {
				Type:        schema.TypeString,
				Optional:    true,
				Description: "The region where the Object Store Credential will be created.",
			},
			// Computed values
			"access_key_id": {
				Type:        schema.TypeString,
				Optional:    true,
				Computed:    true,
				Description: "The access key id of the Object Store Credential. It is generated by the provider.",
			},
			"secret_access_key": {
				Type:        schema.TypeString,
				Optional:    true,
				Computed:    true,
				Description: "The secret access key of the Object Store Credential. It is generated by the provider.",
			},
			"status": {
				Type:        schema.TypeString,
				Computed:    true,
				Description: "The status of the Object Store Credential.",
			},
		},
		CreateContext: resourceObjectStoreCredentialCreate,
		ReadContext:   resourceObjectStoreCredentialRead,
		UpdateContext: resourceObjectStoreCredentialUpdate,
		DeleteContext: resourceObjectStoreCredentialDelete,
		Importer: &schema.ResourceImporter{
			StateContext: schema.ImportStatePassthroughContext,
		},
		Timeouts: &schema.ResourceTimeout{
			Create: schema.DefaultTimeout(30 * time.Minute),
		},
	}
}

// Function to create an Object Store Credential
func resourceObjectStoreCredentialCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	apiClient := m.(*civogo.Client)

	// overwrite the region if it is defined in the datasource
	if region, ok := d.GetOk("region"); ok {
		apiClient.Region = region.(string)
	}

	log.Printf("[INFO] configuring the Object Store Credential %s", d.Get("name").(string))
	config := &civogo.CreateObjectStoreCredentialRequest{
		Name:   d.Get("name").(string),
		Region: apiClient.Region,
	}

	if v, ok := d.GetOk("access_key_id"); ok {
		AccessKeyID := v.(string)
		config.AccessKeyID = &AccessKeyID
	}

	if v, ok := d.GetOk("secret_access_key"); ok {
		SecretAccessKeyID := v.(string)
		config.SecretAccessKeyID = &SecretAccessKeyID
	}

	log.Printf("[INFO] creating the Object Store Credential %s", d.Get("name").(string))
	storeCredential, err := apiClient.NewObjectStoreCredential(config)
	if err != nil {
		return diag.Errorf("[ERR] failed to create Object Store Credential: %s", err)
	}

	d.SetId(storeCredential.ID)

	createStateConf := &resource.StateChangeConf{
		Pending: []string{"pending"},
		Target:  []string{"ready"},
		Refresh: func() (interface{}, string, error) {
			resp, err := apiClient.GetObjectStoreCredential(d.Id())
			if err != nil {
				return 0, "", err
			}
			return resp, resp.Status, nil
		},
		Timeout:        60 * time.Minute,
		Delay:          3 * time.Second,
		MinTimeout:     3 * time.Second,
		NotFoundChecks: 60,
	}
	_, err = createStateConf.WaitForStateContext(ctx)
	if err != nil {
		return diag.Errorf("error waiting for Object Store Credential (%s) to be created: %s", d.Id(), err)
	}

	return resourceObjectStoreCredentialRead(ctx, d, m)
}

// Function to read Object Store Credential
func resourceObjectStoreCredentialRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	apiClient := m.(*civogo.Client)

	// overwrite the region if it is defined in the datasource
	if region, ok := d.GetOk("region"); ok {
		apiClient.Region = region.(string)
	}

	log.Printf("[INFO] retriving the Object Store Credential %s", d.Id())
	resp, err := apiClient.GetObjectStoreCredential(d.Id())
	if err != nil {
		if resp == nil {
			d.SetId("")
			return nil
		}
		return diag.Errorf("[ERR] failed to retrive the Object Store Credential: %s", err)
	}

	d.Set("name", resp.Name)
	d.Set("access_key_id", resp.AccessKeyID)
	d.Set("secret_access_key", resp.SecretAccessKeyID)
	d.Set("status", resp.Status)

	return nil
}

// Function to update the Object Store Credential
func resourceObjectStoreCredentialUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	apiClient := m.(*civogo.Client)

	// overwrite the region if it is defined in the datasource
	if region, ok := d.GetOk("region"); ok {
		apiClient.Region = region.(string)
	}

	_, err := apiClient.FindObjectStoreCredential(d.Id())
	if err != nil {
		return diag.Errorf("[ERR] failed to find Object Store Credential: %s", err)
	}

	config := &civogo.UpdateObjectStoreCredentialRequest{
		Region: apiClient.Region,
	}

	if d.HasChange("access_key_id") {
		accessKeyID := d.Get("access_key_id").(string)
		config.AccessKeyID = &accessKeyID
	}

	if d.HasChange("secret_access_key") {
		secretKey := d.Get("secret_access_key").(string)
		config.SecretAccessKeyID = &secretKey
	}

	log.Printf("[INFO] updating the Object Store Credential %s", d.Id())
	_, err = apiClient.UpdateObjectStoreCredential(d.Id(), config)
	if err != nil {
		return diag.Errorf("[ERR] failed to update Object Store Credential: %s", err)
	}

	return resourceObjectStoreCredentialRead(ctx, d, m)
}

// Function to delete an Object Store Credential
func resourceObjectStoreCredentialDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	apiClient := m.(*civogo.Client)

	// overwrite the region if it is defined in the datasource
	if region, ok := d.GetOk("region"); ok {
		apiClient.Region = region.(string)
	}

	log.Printf("[INFO] deleting the Object Store Credential %s", d.Id())
	_, err := apiClient.DeleteObjectStoreCredential(d.Id())
	if err != nil {
		return diag.Errorf("[ERR] an error occurred while trying to delete the Object Store Credential %s", d.Id())
	}
	return nil
}
