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

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

	diags := diag.Diagnostics{}

	route, diags := utilities.VINSStaticRouteDataSourceCheckPresence(ctx, uint64(state.VinsID.ValueInt64()), uint64(state.RouteID.ValueInt64()), c)
	if diags.HasError() {
		return diags
	}

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

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

		Id:          types.StringValue(id.String()),
		Destination: types.StringValue(route.Destination),
		Gateway:     types.StringValue(route.Gateway),
		GUID:        types.StringValue(route.GUID),
		Netmask:     types.StringValue(route.Netmask),
	}

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

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