package flattens

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

	"github.com/google/uuid"
	"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/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/disks/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/disks/utilities"
)

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

	diags := diag.Diagnostics{}

	diskId := uint64(state.DiskID.ValueInt64())

	recordDisk, err := utilities.DataSourceDiskCheckPresence(ctx, diskId, c)
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot get info about disk with ID %v", diskId), err.Error())
		return diags
	}

	tflog.Info(ctx, "flattens.DiskDataSource: before flatten", map[string]any{"disk_id": diskId, "recordDisk": recordDisk})

	id := uuid.New()
	diskAcl, _ := json.Marshal(recordDisk.ACL)
	*state = models.DataSourceDiskModel{
		DiskID:   state.DiskID,
		Timeouts: state.Timeouts,

		// computed fields
		Id:              types.StringValue(id.String()),
		AccountID:       types.Int64Value(int64(recordDisk.AccountID)),
		AccountName:     types.StringValue(recordDisk.AccountName),
		ACL:             types.StringValue(string(diskAcl)),
		Computes:        flattenComputes(ctx, recordDisk.Computes),
		CreatedTime:     types.Int64Value(int64(recordDisk.CreatedTime)),
		DeletedTime:     types.Int64Value(int64(recordDisk.DeletedTime)),
		Description:     types.StringValue(recordDisk.Description),
		DestructionTime: types.Int64Value(int64(recordDisk.DestructionTime)),
		DeviceName:      types.StringValue(recordDisk.DeviceName),
		GID:             types.Int64Value(int64(recordDisk.GID)),
		ImageID:         types.Int64Value(int64(recordDisk.ImageID)),
		Name:            types.StringValue(recordDisk.Name),
		Order:           types.Int64Value(int64(recordDisk.Order)),
		Params:          types.StringValue(recordDisk.Params),
		ParentID:        types.Int64Value(int64(recordDisk.ParentID)),
		PCISlot:         types.Int64Value(int64(recordDisk.PCISlot)),
		Pool:            types.StringValue(recordDisk.Pool),
		PurgeTime:       types.Int64Value(int64(recordDisk.PurgeTime)),
		ResID:           types.StringValue(recordDisk.ResID),
		ResName:         types.StringValue(recordDisk.ResName),
		Role:            types.StringValue(recordDisk.Role),
		SepID:           types.Int64Value(int64(recordDisk.SepID)),
		SepType:         types.StringValue(recordDisk.SepType),
		Shareable:       types.BoolValue(recordDisk.Shareable),
		SizeMax:         types.Int64Value(int64(recordDisk.SizeMax)),
		SizeUsed:        types.Float64Value(recordDisk.SizeUsed),
		Snapshots:       flattenSnapshots(ctx, recordDisk.Snapshots),
		Status:          types.StringValue(recordDisk.Status),
		TechStatus:      types.StringValue(recordDisk.TechStatus),
		Type:            types.StringValue(recordDisk.Type),
		VMID:            types.Int64Value(int64(recordDisk.VMID)),
	}

	state.Images, diags = types.ListValueFrom(ctx, types.StringType, recordDisk.Images)
	if diags != nil {
		tflog.Error(ctx, fmt.Sprint("flattens.DiskDataSource: cannot flatten recordDisk.Images to state.Images", diags))
	}
	state.PresentTo, diags = types.ListValueFrom(ctx, types.Int64Type, recordDisk.PresentTo)
	if diags != nil {
		tflog.Error(ctx, fmt.Sprint("flattens.DiskDataSource: cannot flatten recordDisk.PresentTo to state.PresentTo", diags))
	}

	iotune := models.IOTuneModel{
		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)),
	}
	obj, diags := types.ObjectValueFrom(ctx, models.ItemIOTune, iotune)
	if diags != nil {
		tflog.Error(ctx, fmt.Sprint("Error flattens.DiskDataSource iotune struct to obj", diags))
	}
	state.IOTune = obj

	tflog.Info(ctx, "flattens.DiskDataSource: end flatten", map[string]any{"disk_id": state.DiskID.ValueInt64()})
	return nil
}
