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

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

	diags := diag.Diagnostics{}

	serivceId := uint64(state.ServiceID.ValueInt64())

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

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

	*state = models.ListInfoSnapshotsModel{
		ServiceID:  state.ServiceID,
		Timeouts:   state.Timeouts,
		EntryCount: types.Int64Value(int64(record.EntryCount)),
	}

	dataList := make([]models.ItemSnapshotsModel, 0, len(record.Data))
	for _, v := range record.Data {
		temp := models.ItemSnapshotsModel{
			GUID:      types.StringValue(v.GUID),
			Label:     types.StringValue(v.Label),
			Timestamp: types.Int64Value(int64(v.Timestamp)),
			Valid:     types.BoolValue(v.Valid),
		}
		dataList = append(dataList, temp)
	}

	state.Data = dataList

	tflog.Info(ctx, "flattens.BServiceSnapshotListDataSource: after flatten", map[string]any{"service_id": state.ServiceID.ValueInt64()})

	tflog.Info(ctx, "End flattens.BServiceSnapshotListDataSource", map[string]any{"service_id": state.ServiceID.ValueInt64()})
	return nil
}
