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/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/flattens"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/dpdknet/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/dpdknet/utilities"
)

func DPDKListDataSource(ctx context.Context, state *models.DataSourceDPDKListModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start flattens.DPDKListDataSource")

	diags := diag.Diagnostics{}

	dpdkList, err := utilities.DPDKListDataSourceCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Cannot get info about list DPDK", err.Error())
		return diags
	}

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

	id := uuid.New()
	*state = models.DataSourceDPDKListModel{
		ByID:       state.ByID,
		GID:        state.GID,
		Name:       state.Name,
		Desc:       state.Desc,
		Status:     state.Status,
		ComputeIDs: state.ComputeIDs,
		SortBy:     state.SortBy,
		Page:       state.Page,
		Size:       state.Size,
		Timeouts:   state.Timeouts,

		Id: types.StringValue(id.String()),
	}

	items := make([]models.ItemDPDKListModel, 0, len(dpdkList.Data))
	for _, dpdkItem := range dpdkList.Data {

		item := models.ItemDPDKListModel{
			AccountAccess: flattens.FlattenSimpleTypeToList(ctx, types.Int64Type, dpdkItem.AccountAccess),
			CreatedTime:   types.Int64Value(int64(dpdkItem.CreatedTime)),
			Desc:          types.StringValue(dpdkItem.Description),
			DPDKID:        types.Int64Value(int64(dpdkItem.ID)),
			GID:           types.Int64Value(int64(dpdkItem.GID)),
			GUID:          types.Int64Value(int64(dpdkItem.GUID)),
			Name:          types.StringValue(dpdkItem.Name),
			RGAccess:      flattens.FlattenSimpleTypeToList(ctx, types.Int64Type, dpdkItem.RGAccess),
			Status:        types.StringValue(dpdkItem.Status),
			OVSBridge:     types.StringValue(dpdkItem.OVSBridge),
			VlanID:        types.Int64Value(int64(dpdkItem.VlanID)),
			ComputeIDs:    flattens.FlattenSimpleTypeToList(ctx, types.Int64Type, dpdkItem.ComputeIDs),
			UpdatedTime:   types.Int64Value(int64(dpdkItem.UpdatedTime)),
		}

		items = append(items, item)
	}

	state.Items = items
	state.EntryCount = types.Int64Value(int64(dpdkList.EntryCount))

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