package flattens

import (
	"context"

	"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/decort-golang-sdk/pkg/cloudapi/compute"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/kvmvm/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/kvmvm/utilities"
)

func DataSourceComputeVGPUList(ctx context.Context, state *models.ListVGPUsModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start FlattenDataSourceComputeVGPUList")

	diags := diag.Diagnostics{}

	vgpuList, err := utilities.ComputeVGPUListCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Error get compute vgpu list info", err.Error())
		return diags
	}

	id := uuid.New()

	*state = models.ListVGPUsModel{
		ComputeID:      state.ComputeID,
		GPUID:          state.GPUID,
		Type:           state.Type,
		Status:         state.Status,
		SortBy:         state.SortBy,
		Page:           state.Page,
		Size:           state.Size,
		IncludeDeleted: state.IncludeDeleted,
		Timeouts:       state.Timeouts,
		Id:             types.StringValue(id.String()),
		Items:          flattenVGPU(ctx, vgpuList.Data),
		EntryCount:     types.Int64Value(int64(vgpuList.EntryCount)),
	}

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

func flattenVGPU(ctx context.Context, vgpuList []compute.ItemVGPU) []models.ItemVGPU {
	tflog.Info(ctx, "Start flattenVGPUItems")

	res := make([]models.ItemVGPU, 0, len(vgpuList))
	for _, item := range vgpuList {
		temp := models.ItemVGPU{
			AccountID:      types.Int64Value(int64(item.AccountID)),
			CreatedTime:    types.Int64Value(int64(item.CreatedTime)),
			DeletedTime:    types.Int64Value(int64(item.DeletedTime)),
			GID:            types.Int64Value(int64(item.GID)),
			GUID:           types.Int64Value(int64(item.GUID)),
			ID:             types.Int64Value(int64(item.ID)),
			LastClaimedBy:  types.Int64Value(int64(item.LastClaimedBy)),
			LastUpdateTime: types.Int64Value(int64(item.LastUpdateTime)),
			Mode:           types.StringValue(item.Mode),
			PCISlot:        types.Int64Value(int64(item.PCISlot)),
			PGPUID:         types.Int64Value(int64(item.PGPUID)),
			ProfileID:      types.Int64Value(int64(item.ProfileID)),
			RAM:            types.Int64Value(int64(item.RAM)),
			ReferenceID:    types.StringValue(item.ReferenceID),
			RGID:           types.Int64Value(int64(item.RGID)),
			Status:         types.StringValue(item.Status),
			Type:           types.StringValue(item.Type),
			VMID:           types.Int64Value(int64(item.VMID)),
		}
		res = append(res, temp)
	}

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