package flattens

import (
	"context"
	"fmt"

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

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

	diags := diag.Diagnostics{}

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

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

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

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

	var diagsItem diag.Diagnostics
	state.Ids, diagsItem = types.ListValueFrom(ctx, types.Int64Type, agItem)
	if diagsItem.HasError() {
		tflog.Error(ctx, fmt.Sprint("flattens.RGAffinityGroupsGetDataSource: cannot flatten agItem to state.Ids", diags))
	}

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

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