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

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

	diags := diag.Diagnostics{}

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

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

	id := uuid.New()
	*state = models.DataSourceAccountTemplatesListModel{
		AccountID:      state.AccountID,
		IncludeDeleted: state.IncludeDeleted,
		ImageID:        state.ImageID,
		Name:           state.Name,
		Type:           state.Type,
		SortBy:         state.SortBy,
		Page:           state.Page,
		Size:           state.Size,
		Timeouts:       state.Timeouts,

		Id:         types.StringValue(id.String()),
		EntryCount: types.Int64Value(int64(templatesList.EntryCount)),
	}

	items := make([]models.ItemTemplateModel, 0, len(templatesList.Data))
	for _, item := range templatesList.Data {
		i := models.ItemTemplateModel{
			UNCPath:     types.StringValue(item.UNCPath),
			AccountID:   types.Int64Value(int64(item.AccountID)),
			Description: types.StringValue(item.Description),
			ID:          types.Int64Value(int64(item.ID)),
			Name:        types.StringValue(item.Name),
			Public:      types.BoolValue(item.Public),
			Size:        types.Int64Value(int64(item.Size)),
			Status:      types.StringValue(item.Status),
			Type:        types.StringValue(item.Type),
			Username:    types.StringValue(item.Username),
		}

		items = append(items, i)
	}
	state.Items = items

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