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

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

	diags := diag.Diagnostics{}

	disksList, err := utilities.AccountDisksListCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("flattens.AccountDisksListDataSource: Cannot get info", err.Error())
		return diags
	}

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

	id := uuid.New()
	*state = models.DataSourceAccountDisksListModel{
		AccountID:   state.AccountID,
		DiskID:      state.DiskID,
		Name:        state.Name,
		DiskMaxSize: state.DiskMaxSize,
		Type:        state.Type,
		Page:        state.Page,
		Size:        state.Size,
		Timeouts:    state.Timeouts,
		SortBy:      state.SortBy,

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

	items := make([]models.ItemDiskModel, 0, len(disksList.Data))
	for _, item := range disksList.Data {
		i := models.ItemDiskModel{
			DiskID:    types.Int64Value(int64(item.ID)),
			DiskName:  types.StringValue(item.Name),
			Pool:      types.StringValue(item.Pool),
			SEPID:     types.Int64Value(int64(item.SepID)),
			Shareable: types.BoolValue(item.Shareable),
			SizeMax:   types.Int64Value(int64(item.SizeMax)),
			Type:      types.StringValue(item.Type),
		}
		items = append(items, i)
	}
	state.Items = items

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

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