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

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

	diags := diag.Diagnostics{}

	vinsId := uint64(state.VinsID.ValueInt64())

	natRulesList, diags := utilities.VINSNATRuleListDataSourceCheckPresence(ctx, vinsId, c)
	if diags.HasError() {
		return diags
	}

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

	id := uuid.New()
	*state = models.DataSourceVINSNATRuleListModel{
		VinsID:   state.VinsID,
		Timeouts: state.Timeouts,

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

	items := make([]models.ItemVINSNATRuleModel, 0, len(natRulesList.Data))
	for _, item := range natRulesList.Data {
		v := models.ItemVINSNATRuleModel{
			ID:              types.Int64Value(int64(item.ID)),
			LocalIP:         types.StringValue(item.LocalIP),
			LocalPort:       types.Int64Value(int64(item.LocalPort)),
			Protocol:        types.StringValue(item.Protocol),
			PublicPortEnd:   types.Int64Value(int64(item.PublicPortEnd)),
			PublicPortStart: types.Int64Value(int64(item.PublicPortStart)),
			VMID:            types.Int64Value(int64(item.VMID)),
			VMName:          types.StringValue(item.VMName),
		}
		items = append(items, v)
	}
	state.Items = items

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