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"
)

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

	diags := diag.Diagnostics{}

	rgListPFW, err := utilities.RGListPFWCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Cannot get info about resource group list pfw", err.Error())
		return diags
	}

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

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

		Id: types.StringValue(id.String()),
	}

	items := make([]models.ItemsRGListPFWModel, 0, len(rgListPFW.Data))
	for _, pfwItem := range rgListPFW.Data {
		item := models.ItemsRGListPFWModel{
			PublicPortEnd:   types.Int64Value(int64(pfwItem.PublicPortEnd)),
			PublicPortStart: types.Int64Value(int64(pfwItem.PublicPortStart)),
			VMID:            types.Int64Value(int64(pfwItem.VMID)),
			VMIP:            types.StringValue(pfwItem.VMIP),
			VMName:          types.StringValue(pfwItem.VMName),
			VMPort:          types.Int64Value(int64(pfwItem.VMPort)),
			VINSID:          types.Int64Value(int64(pfwItem.VINSID)),
			VINSName:        types.StringValue(pfwItem.VINSName),
		}

		items = append(items, item)
	}

	state.Items = items
	state.EntryCount = types.Int64Value(int64(rgListPFW.EntryCount))

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

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