package flattens

import (
	"context"

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

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

	diags := diag.Diagnostics{}

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

	tflog.Info(ctx, "flattens.StackListDataSource: before flatten", map[string]any{"record": record})

	*state = models.ListStacksModel{
		//optional fields
		Timeouts: state.Timeouts,
		ByID:     state.ByID,
		Name:     state.Name,
		Status:   state.Status,
		Type:     state.Type,
		SortBy:   state.SortBy,
		Page:     state.Page,
		Size:     state.Size,

		//compute fields
		EntryCount: types.Int64Value(int64(record.EntryCount)),
	}

	items := make([]models.ItemStackModel, 0, len(record.Data))
	for _, item := range record.Data {
		i := models.ItemStackModel{
			ID:     types.Int64Value(int64(item.ID)),
			Name:   types.StringValue(item.Name),
			Status: types.StringValue(item.Status),
			Type:   types.StringValue(item.Type),
		}
		items = append(items, i)
	}
	state.Data = items

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

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