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/service/cloudbroker/rg/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudbroker/rg/utilities"
)

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

	diags := diag.Diagnostics{}

	agList, err := utilities.RGAffinityGroupsListCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Cannot get info about resource group affinity groups list", err.Error())
		return diags
	}

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

	id := uuid.New()
	*state = models.DataSourceRGAffinityGroupsListModel{
		RGID: state.RGID,

		Page:     state.Page,
		Size:     state.Size,
		Timeouts: state.Timeouts,

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

	items := make([]models.ItemAffinityGroupModel, 0, len(agList.Data))
	for _, data := range agList.Data {
		for agLabel, listAG := range data {
			item := models.ItemAffinityGroupModel{
				Label: types.StringValue(agLabel),
			}

			ids := make([]models.ItemIDModel, 0, len(listAG))
			for _, agItem := range listAG {
				idItem := models.ItemIDModel{
					Id:     types.Int64Value(int64(agItem.ID)),
					NodeId: types.Int64Value(int64(agItem.NodeID)),
				}
				ids = append(ids, idItem)
			}
			item.Ids = ids
			items = append(items, item)
		}
	}
	state.AffinityGroups = items
	state.EntryCount = types.Int64Value(int64(agList.EntryCount))

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

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