package flattens

import (
	"context"
	"fmt"

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

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

	diags := diag.Diagnostics{}

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

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

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

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

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

	items := make([]models.ItemVinsStaticRouteModel, 0, len(routesList.Data))
	for _, item := range routesList.Data {
		v := models.ItemVinsStaticRouteModel{
			Destination: types.StringValue(item.Destination),
			Gateway:     types.StringValue(item.Gateway),
			GUID:        types.StringValue(item.GUID),
			ID:          types.Int64Value(int64(item.ID)),
			Netmask:     types.StringValue(item.Netmask),
		}

		v.ComputeIds, diags = types.ListValueFrom(ctx, types.Int64Type, item.ComputeIds)
		if diags.HasError() {
			tflog.Error(ctx, fmt.Sprint("Error flattens.VINSStaticRouteListDataSource: cannot flatten item.ComputeIds to v.ComputeIds", diags))
		}

		items = append(items, v)
	}
	state.Items = items

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