/*
Copyright (c) 2019-2024 Digital Energy Cloud Solutions LLC. All Rights Reserved.
Authors:
Petr Krutov, <petr.krutov@digitalenergy.online>
Stanislav Solovev, <spsolovev@digitalenergy.online>

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

/*
Terraform DECORT provider - manage resources provided by DECORT (Digital Energy Cloud
Orchestration Technology) with Terraform by Hashicorp.

Source code: https://repository.basistech.ru/BASIS/terraform-provider-decort

Please see README.md to learn where to place source code so that it
builds seamlessly.

Documentation: https://repository.basistech.ru/BASIS/terraform-provider-decort/wiki
*/

package disks

import (
	"context"
	"strconv"

	"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
	log "github.com/sirupsen/logrus"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/disks"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/constants"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/controller"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/dc"
	"repository.basistech.ru/BASIS/terraform-provider-decort/internal/service/cloudbroker/ic"
)

func resourceDiskReplicationCreate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	diskId := uint64(d.Get("disk_id").(int))

	log.Debugf("resourceDiskReplicationCreate: called for disk with ID: %d", diskId)

	c := m.(*controller.ControllerCfg)

	err := ic.ExistDiskID(ctx, diskId, m)
	if err != nil {
		return diag.FromErr(err)
	}

	reqCreate := disks.ReplicateRequest{
		DiskID:   diskId,
		Name:     d.Get("disk_name").(string),
		SepID:    uint64(d.Get("sep_id").(int)),
		PoolName: d.Get("pool_name").(string),
	}

	diskReplicaId, err := c.CloudBroker().Disks().Replicate(ctx, reqCreate)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	d.SetId(strconv.FormatUint(diskReplicaId, 10))
	d.Set("replica_disk_id", diskReplicaId)

	log.Debugf("resourceDiskReplicationCreate: create replica complete for disk with ID: %d", diskId)

	warnings := dc.Warnings{}

	if start, ok := d.GetOk("start"); ok && !start.(bool) {
		log.Debugf("resourceDiskReplicationCreate: replication between disk with ID: %d and replica with ID: %d, try to stop", diskId, diskReplicaId)
		reqStop := disks.ReplicationStopRequest{
			DiskID: diskId,
		}
		_, err = c.CloudBroker().Disks().ReplicationStop(ctx, reqStop)
		if err != nil {
			warnings.Add(err)
		}
		log.Debugf("resourceDiskReplicationCreate: replication between disk with ID: %d and replica with ID: %d, stoped", diskId, diskReplicaId)
	}
	return append(resourceDiskReplicationRead(ctx, d, m), warnings.Get()...)
}

func resourceDiskReplicationRead(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	log.Debugf("resourceDiskReplicationRead: called for disk with ID: %s", d.Id())
	c := m.(*controller.ControllerCfg)

	req := disks.ReplicationStatusRequest{
		DiskID: uint64(d.Get("disk_id").(int)),
	}

	status, err := c.CloudBroker().Disks().ReplicationStatus(ctx, req)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	diskReplica, err := utilityDiskReplicaCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	flattenDiskReplica(d, diskReplica, status)

	log.Debugf("resourceDiskReplicationRead: read complete for disk with ID: %s", d.Id())
	return nil
}

func resourceDiskReplicationUpdate(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	diskId := uint64(d.Get("disk_id").(int))
	log.Debugf("resourceDiskReplicationUpdate: called for disk with ID: %d", diskId)

	err := ic.ExistDiskID(ctx, diskId, m)
	if err != nil {
		return diag.FromErr(err)
	}

	if d.HasChange("start") {
		if err := utilityDiskReplicationUpdateStartStop(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("pause") {
		if err := utilityDiskReplicationUpdatePause(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	}

	if d.HasChange("reverse") {
		if err := utilityDiskReplicationUpdateReverse(ctx, d, m); err != nil {
			return diag.FromErr(err)
		}
	}

	log.Debugf("resourceDiskReplicationUpdate: read complete for disk with ID: %d", diskId)
	return resourceDiskReplicationRead(ctx, d, m)
}

func resourceDiskReplicationDelete(ctx context.Context, d *schema.ResourceData, m interface{}) diag.Diagnostics {
	diskId := uint64(d.Get("disk_id").(int))
	log.Debugf("resourceDiskReplicationDelete: called for disk with ID: %d", diskId)

	disk, err := utilityDiskReplicaCheckPresence(ctx, d, m)
	if err != nil {
		d.SetId("")
		return diag.FromErr(err)
	}

	c := m.(*controller.ControllerCfg)

	if d.Get("start").(bool) {
		reqStop := disks.ReplicationStopRequest{
			DiskID: uint64(d.Get("disk_id").(int)),
		}

		log.Debugf("resourceDiskReplicationDelete: stop replication for disk with ID: %d", diskId)
		_, err = c.CloudBroker().Disks().ReplicationStop(ctx, reqStop)
		if err != nil {
			return diag.FromErr(err)
		}
		log.Debugf("resourceDiskReplicationDelete: stop replication for disk with ID: %d, complete", diskId)
	}

	reqDelete := disks.DeleteRequest{
		DiskID:      disk.ID,
		Detach:      d.Get("detach").(bool),
		Permanently: d.Get("permanently").(bool),
	}

	log.Debugf("resourceDiskReplicationDelete: delete disk replica for disk with ID: %d", diskId)
	_, err = c.CloudBroker().Disks().Delete(ctx, reqDelete)
	if err != nil {
		return diag.FromErr(err)
	}
	log.Debugf("resourceDiskReplicationDelete: delete disk replica for disk with ID: %d, complete", diskId)

	d.SetId("")

	return nil
}

func ResourceDiskReplication() *schema.Resource {
	return &schema.Resource{
		SchemaVersion: 1,

		CreateContext: resourceDiskReplicationCreate,
		ReadContext:   resourceDiskReplicationRead,
		UpdateContext: resourceDiskReplicationUpdate,
		DeleteContext: resourceDiskReplicationDelete,

		Importer: &schema.ResourceImporter{
			StateContext: schema.ImportStatePassthroughContext,
		},

		Timeouts: &schema.ResourceTimeout{
			Create:  &constants.Timeout600s,
			Read:    &constants.Timeout300s,
			Update:  &constants.Timeout300s,
			Delete:  &constants.Timeout300s,
			Default: &constants.Timeout300s,
		},

		Schema: resourceDiskReplicationSchemaMake(),
	}
}
