package flattens

import (
	"context"
	"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/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/flattens"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/vfpool/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/vfpool/utilities"
)

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

	diags := diag.Diagnostics{}

	vfPoolID := uint64(state.VFPoolID.ValueInt64())

	record, err := utilities.VFPoolCheckPresence(ctx, vfPoolID, c)
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot get info about VFpool with ID %v", vfPoolID), err.Error())
		return diags
	}

	tflog.Info(ctx, "flattens.VFPoolDataSource: before flatten", map[string]any{"record": record})

	*state = models.ItemVFPoolModel{
		//required fields
		VFPoolID: state.VFPoolID,

		//optional fields
		Timeouts: state.Timeouts,

		//compute fields
		AccountAccess: flattens.FlattenSimpleTypeToList(ctx, types.Int64Type, record.AccountAccess),

		CreatedTime: types.Int64Value(int64(record.CreatedTime)),
		Description: types.StringValue(record.Description),
		GID:         types.Int64Value(int64(record.GID)),
		GUID:        types.Int64Value(int64(record.GUID)),
		Name:        types.StringValue(record.Name),
		RGAccess:    flattens.FlattenSimpleTypeToList(ctx, types.Int64Type, record.RGAccess),
		Status:      types.StringValue(record.Status),
		UpdatedTime: types.Int64Value(int64(record.UpdatedTime)),
	}

	items := make([]models.VFSModel, 0, len(record.VFS))
	for _, vfsItem := range record.VFS {
		i := models.VFSModel{
			NodeID: types.Int64Value(int64(vfsItem.NodeID)),
		}

		vfList := make([]models.VFItemModel, 0, len(vfsItem.VFList))
		for _, vfItem := range vfsItem.VFList {
			vfI := models.VFItemModel{
				NicName: types.StringValue(vfItem.NicName),
			}

			vfInfoList := make([]models.VFSInfoItemModel, 0, len(vfItem.VFSInfo))
			for _, vfsInfoItem := range vfItem.VFSInfo {
				vfsInfoI := models.VFSInfoItemModel{
					ID:      types.Int64Value(int64(vfsInfoItem.ID)),
					Claimed: types.BoolValue(vfsInfoItem.Claimed),
					VMID:    types.Int64Value(int64(vfsInfoItem.VMID)),
				}

				vfInfoList = append(vfInfoList, vfsInfoI)

			}

			vfI.VFSInfo = vfInfoList
			vfList = append(vfList, vfI)

		}

		i.VFList = vfList
		items = append(items, i)
	}
	state.VFS = items

	tflog.Info(ctx, "flattens.VFPoolDataSource: after flatten")

	tflog.Info(ctx, "End flattens.VFPoolDataSource")
	return nil
}
