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 DataSourceComputePciDeviceList(ctx context.Context, state *models.ListPCIDevicesModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start FlattenDataSourceComputePciDeviceList")

	diags := diag.Diagnostics{}

	pciDeviceList, err := utilities.ComputePciDeviceListCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Error get compute pci device list info", err.Error())
		return diags
	}

	id := uuid.New()

	*state = models.ListPCIDevicesModel{
		ComputeID: state.ComputeID,
		RGID:      state.RGID,
		DevID:     state.DevID,
		Name:      state.Name,
		Status:    state.Status,
		SortBy:    state.SortBy,
		Page:      state.Page,
		Size:      state.Size,
		Timeouts:  state.Timeouts,

		Id:         types.StringValue(id.String()),
		Items:      flattenPCIDevice(ctx, pciDeviceList.Data),
		EntryCount: types.Int64Value(int64(pciDeviceList.EntryCount)),
	}

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

func flattenPCIDevice(ctx context.Context, deviceList []compute.ItemPCIDevice) []models.ItemPCIDevice {
	tflog.Info(ctx, "Start flattenPCIDevice")

	res := make([]models.ItemPCIDevice, 0, len(deviceList))
	for _, item := range deviceList {
		temp := models.ItemPCIDevice{
			ComputeID:   types.Int64Value(int64(item.ComputeID)),
			Description: types.StringValue(item.Description),
			GUID:        types.Int64Value(int64(item.GUID)),
			HwPath:      types.StringValue(item.HwPath),
			ID:          types.Int64Value(int64(item.ID)),
			Name:        types.StringValue(item.Name),
			RGID:        types.Int64Value(int64(item.RGID)),
			StackID:     types.Int64Value(int64(item.StackID)),
			Status:      types.StringValue(item.Status),
			SystemName:  types.StringValue(item.SystemName),
		}
		res = append(res, temp)
	}

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