package flattens

import (
	"context"
	"fmt"

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

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

	diags := diag.Diagnostics{}

	id := uint64(state.StackID.ValueInt64())

	record, err := utilities.StackCheckPresence(ctx, id, c)
	if err != nil {
		diags.AddError(fmt.Sprintf("Cannot get info about stack with ID %v", id), err.Error())
		return diags
	}

	tflog.Info(ctx, "flattens.StackDataSource: before flatten", map[string]any{"stack_id": state.StackID.ValueInt64(), "record": record})

	*state = models.InfoStackModel{
		StackID:  state.StackID,
		Timeouts: state.Timeouts,

		CPUAllocationRatio: types.Float64Value(record.CPUAllocationRatio),
		Descr:              types.StringValue(record.Descr),
		Drivers:            flattens.FlattenSimpleTypeToList(ctx, types.StringType, record.Drivers),
		MemAllocationRatio: types.Float64Value(record.MemAllocationRatio),
		Name:               types.StringValue(record.Name),
		Status:             types.StringValue(record.Status),
		Type:               types.StringValue(record.Type),
	}

	tflog.Info(ctx, "flattens.StackDataSource: after flatten", map[string]any{"stack_id": state.StackID.ValueInt64()})

	tflog.Info(ctx, "End flattens.StackDataSource", map[string]any{"stack_id": state.StackID.ValueInt64()})
	return nil
}
