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

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

	diags := diag.Diagnostics{}

	usageInfo, err := utilities.RGUsageCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Cannot get info about resource group usage", err.Error())
		return diags
	}

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

	id := uuid.New()
	*state = models.DataSourceRGUsageModel{
		RGID: state.RGID,

		Timeouts: state.Timeouts,
		Id:       types.StringValue(id.String()),

		CPU:         types.Int64Value(int64(usageInfo.CPU)),
		DiskSize:    types.Int64Value(int64(usageInfo.DiskSize)),
		DiskSizeMax: types.Int64Value(int64(usageInfo.DiskSizeMax)),
		ExtIPs:      types.Int64Value(int64(usageInfo.ExtIPs)),
		ExtTraffic:  types.Int64Value(int64(usageInfo.ExtTraffic)),
		GPU:         types.Int64Value(int64(usageInfo.GPU)),
		RAM:         types.Int64Value(int64(usageInfo.RAM)),
		SEPs:        flattenSEPs(ctx, usageInfo.SEPs),
	}

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

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