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

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

	diags := diag.Diagnostics{}

	templatesList, err := utilities.AccountAvailableTemplatesListDataSourceCheckPresence(ctx, uint64(state.AccountID.ValueInt64()), c)
	if err != nil {
		diags.AddError("Cannot get info about templates list", err.Error())
		return diags
	}

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

	*state = models.DataSourceAccountAvailableTemplatesListModel{
		AccountID: state.AccountID,
		Timeouts:  state.Timeouts,
		Items:     flattens.FlattenSimpleTypeToList(ctx, types.Int64Type, templatesList),
	}

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

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