package flattens

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/hashicorp/terraform-plugin-framework/diag"
	"github.com/hashicorp/terraform-plugin-framework/types"
	"github.com/hashicorp/terraform-plugin-log/tflog"
	"repository.basistech.ru/BASIS/decort-golang-sdk/pkg/cloudbroker/disks"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/flattens"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/disks/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/disks/utilities"
)

// DiskReplicationDataSource flattens data source for disk.
// Return error in case data source is not found on the platform.
// Flatten errors are added to tflog.
func DiskReplicationDataSource(ctx context.Context, state *models.RecordDiskModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start flattens.DiskReplicationDataSource")

	diags := diag.Diagnostics{}

	recordDisk, status, err := utilities.DataSourceDiskReplicationCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot get info about disk"), err.Error())
		return diags
	}

	tflog.Info(ctx, "flattens.DiskReplicationDataSource: before flatten")

	diskAcl, _ := json.Marshal(recordDisk.ACL)

	*state = models.RecordDiskModel{
		DiskId:              state.DiskId,
		Timeouts:            state.Timeouts,
		ACL:                 types.StringValue(string(diskAcl)),
		BootPartition:       types.Int64Value(int64(recordDisk.BootPartition)),
		AccountID:           types.Int64Value(int64(recordDisk.AccountID)),
		AccountName:         types.StringValue(recordDisk.AccountName),
		Computes:            flattenDRComputes(ctx, recordDisk.Computes),
		CreatedTime:         types.Int64Value(int64(recordDisk.CreatedTime)),
		DeletedTime:         types.Int64Value(int64(recordDisk.DeletedTime)),
		DeviceName:          types.StringValue(recordDisk.DeviceName),
		DiskPath:            types.StringValue(recordDisk.DiskPath),
		Description:         types.StringValue(recordDisk.Description),
		DestructionTime:     types.Int64Value(int64(recordDisk.DestructionTime)),
		GID:                 types.Int64Value(int64(recordDisk.GID)),
		GUID:                types.Int64Value(int64(recordDisk.GUID)),
		ImageID:             types.Int64Value(int64(recordDisk.ImageID)),
		Images:              flattens.FlattenSimpleTypeToList(ctx, types.Int64Type, recordDisk.Images),
		Name:                types.StringValue(recordDisk.Name),
		IQN:                 types.StringValue(recordDisk.IQN),
		Login:               types.StringValue(recordDisk.Login),
		Milestones:          types.Int64Value(int64(recordDisk.Milestones)),
		Order:               types.Int64Value(int64(recordDisk.Order)),
		Params:              types.StringValue(recordDisk.Params),
		ParentID:            types.Int64Value(int64(recordDisk.ParentID)),
		Passwd:              types.StringValue(recordDisk.Password),
		PCISlot:             types.Int64Value(int64(recordDisk.PCISlot)),
		Pool:                types.StringValue(recordDisk.Pool),
		PresentTo:           flattens.FlattenSimpleTypeToList(ctx, types.StringType, recordDisk.PresentTo),
		PurgeAttempts:       types.Int64Value(int64(recordDisk.PurgeAttempts)),
		PurgeTime:           types.Int64Value(int64(recordDisk.PurgeTime)),
		RealityDeviceNumber: types.Int64Value(int64(recordDisk.RealityDeviceNumber)),
		ReferenceID:         types.StringValue(recordDisk.ReferenceID),
		ResID:               types.StringValue(recordDisk.ResID),
		ResName:             types.StringValue(recordDisk.ResName),
		Role:                types.StringValue(recordDisk.Role),
		SepType:             types.StringValue(recordDisk.SEPType),
		SepID:               types.Int64Value(int64(recordDisk.SEPID)),
		Shareable:           types.BoolValue(recordDisk.Shareable),
		SizeMax:             types.Int64Value(int64(recordDisk.SizeMax)),
		SizeUsed:            types.Float64Value(recordDisk.SizeUsed),
		Snapshots:           diskListFlattenSnapshots(ctx, recordDisk.Snapshots),
		Status:              types.StringValue(recordDisk.Status),
		StatusReplication:   types.StringValue(*status),
		TechStatus:          types.StringValue(recordDisk.TechStatus),
		Type:                types.StringValue(recordDisk.Type),
		VMID:                types.Int64Value(int64(recordDisk.VMID)),
	}

	iotune := models.DiskReplicationIOTune{
		ReadBytesSec:     types.Int64Value(int64(recordDisk.IOTune.ReadBytesSec)),
		ReadBytesSecMax:  types.Int64Value(int64(recordDisk.IOTune.ReadBytesSecMax)),
		ReadIOPSSec:      types.Int64Value(int64(recordDisk.IOTune.ReadIOPSSec)),
		ReadIOPSSecMax:   types.Int64Value(int64(recordDisk.IOTune.ReadIOPSSecMax)),
		SizeIOPSSec:      types.Int64Value(int64(recordDisk.IOTune.SizeIOPSSec)),
		TotalBytesSec:    types.Int64Value(int64(recordDisk.IOTune.TotalBytesSec)),
		TotalBytesSecMax: types.Int64Value(int64(recordDisk.IOTune.TotalBytesSecMax)),
		TotalIOPSSec:     types.Int64Value(int64(recordDisk.IOTune.TotalIOPSSec)),
		TotalIOPSSecMax:  types.Int64Value(int64(recordDisk.IOTune.TotalIOPSSecMax)),
		WriteBytesSec:    types.Int64Value(int64(recordDisk.IOTune.WriteBytesSec)),
		WriteBytesSecMax: types.Int64Value(int64(recordDisk.IOTune.WriteBytesSecMax)),
		WriteIOPSSec:     types.Int64Value(int64(recordDisk.IOTune.WriteIOPSSec)),
		WriteIOPSSecMax:  types.Int64Value(int64(recordDisk.IOTune.WriteIOPSSecMax)),
	}
	state.IOTune = &iotune

	itemReplication := models.ItemReplicationModel{
		DiskID:       types.Int64Value(int64(recordDisk.Replication.DiskID)),
		PoolID:       types.StringValue(recordDisk.Replication.PoolID),
		Role:         types.StringValue(recordDisk.Replication.Role),
		SelfVolumeID: types.StringValue(recordDisk.Replication.SelfVolumeID),
		StorageID:    types.StringValue(recordDisk.Replication.StorageID),
		VolumeID:     types.StringValue(recordDisk.Replication.VolumeID),
	}

	state.Replication = &itemReplication

	tflog.Info(ctx, "flattens.ReplicationDiskDataSource: end flatten")
	return nil
}

func flattenDRComputes(ctx context.Context, items map[string]string) types.List {
	tflog.Info(ctx, "Start flattenDRComputes")
	tempSlice := make([]types.Object, 0, len(items))
	for id, name := range items {
		temp := models.ItemComputeModel{
			ComputeId:   types.StringValue(id),
			ComputeName: types.StringValue(name),
		}
		obj, diags := types.ObjectValueFrom(ctx, models.ItemCompute, temp)
		if diags != nil {
			tflog.Error(ctx, fmt.Sprint("Error flattenDRComputes struct to obj", diags))
		}
		tempSlice = append(tempSlice, obj)
	}

	res, diags := types.ListValueFrom(ctx, types.ObjectType{AttrTypes: models.ItemCompute}, tempSlice)
	if diags != nil {
		tflog.Error(ctx, fmt.Sprint("Error flattenDRComputes", diags))
	}

	tflog.Info(ctx, "End flattenDRComputes")
	return res
}

func diskListFlattenSnapshots(ctx context.Context, snapshots disks.ListSnapshots) types.List {
	tflog.Info(ctx, "Start flattenSnapshots")
	tempSlice := make([]types.Object, 0, len(snapshots))
	for _, item := range snapshots {
		temp := models.DiskReplicationItemSnapshot{
			GUID:        types.StringValue(item.GUID),
			Label:       types.StringValue(item.Label),
			ResID:       types.StringValue(item.ResID),
			SnapSetGUID: types.StringValue(item.SnapSetGUID),
			SnapSetTime: types.Int64Value(int64(item.SnapSetTime)),
			TimeStamp:   types.Int64Value(int64(item.Timestamp)),
		}
		obj, diags := types.ObjectValueFrom(ctx, models.DiskReplicationSnapshot, temp)
		if diags != nil {
			tflog.Error(ctx, fmt.Sprint("Error diskListFlattenSnapshots struct to obj", diags))
		}
		tempSlice = append(tempSlice, obj)
	}

	res, diags := types.ListValueFrom(ctx, types.ObjectType{AttrTypes: models.ItemSnapshot}, tempSlice)
	if diags != nil {
		tflog.Error(ctx, fmt.Sprint("Error diskListFlattenSnapshots", diags))
	}

	tflog.Info(ctx, "End diskListFlattenSnapshots")
	return res
}
