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/decort-golang-sdk/pkg/cloudapi/compute"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/client"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/kvmvm/models"
	"repository.basistech.ru/BASIS/terraform-provider-dynamix/internal/service/cloudapi/kvmvm/utilities"
)

func DataSourceComputePFWList(ctx context.Context, state *models.ListPFWsModel, c *client.Client) diag.Diagnostics {
	tflog.Info(ctx, "Start FlattenDataSourceComputePFWList")

	diags := diag.Diagnostics{}

	pfwList, err := utilities.ComputePFWListCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Error get compute pfw list info", err.Error())
		return diags
	}

	id := uuid.New()

	*state = models.ListPFWsModel{
		ComputeID:  state.ComputeID,
		Timeouts:   state.Timeouts,
		Id:         types.StringValue(id.String()),
		Items:      flattenItemsPFWList(ctx, pfwList),
		EntryCount: types.Int64Value(int64(pfwList.EntryCount)),
	}

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

func flattenItemsPFWList(ctx context.Context, pfw *compute.ListPFWs) []models.ItemPFWModel {
	tflog.Info(ctx, "Start flattenItemsPFWList")

	res := make([]models.ItemPFWModel, 0, len(pfw.Data))
	for _, item := range pfw.Data {
		temp := models.ItemPFWModel{
			PFWId:           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)),
		}
		res = append(res, temp)
	}

	tflog.Info(ctx, "End flattenItemsPFWList")
	return res
}
