package flattens

import (
	"context"
	"fmt"
	"time"

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

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

	vinsId, routeId, diags := utilities.GetVinsIDAndRouteID(ctx, plan)
	if diags.HasError() {
		return diags
	}

	recordRoute, diags := utilities.VINSStaticRouteResourceCheckPresence(ctx, vinsId, routeId, c)
	if diags.HasError() {
		return diags
	}

	tflog.Info(ctx, "flattens.VINSStaticRouteResource: before flatten", map[string]any{"id": plan.Id.ValueString()})

	*plan = models.ResourceVINSStaticRouteModel{
		VinsID:      types.Int64Value(int64(vinsId)),
		Destination: types.StringValue(recordRoute.Destination),
		Netmask:     types.StringValue(recordRoute.Netmask),
		Gateway:     types.StringValue(recordRoute.Gateway),
		Timeouts:    plan.Timeouts,

		RouteID:    types.Int64Value(int64(routeId)),
		ComputeIDs: flattens.FlattenSimpleTypeToList(ctx, types.Int64Type, recordRoute.ComputeIds),

		Id:          plan.Id,
		LastUpdated: plan.LastUpdated,
		GUID:        types.StringValue(recordRoute.GUID),
	}

	if plan.Id.IsUnknown() {
		plan.Id = types.StringValue(fmt.Sprintf("%d#%d", vinsId, routeId))
	}

	if plan.LastUpdated.IsUnknown() {
		plan.LastUpdated = types.StringValue(time.Now().Format(time.RFC850))
	}

	tflog.Info(ctx, "flattens.VINSStaticRouteResource: after flatten", map[string]any{"id": plan.Id.ValueString()})

	tflog.Info(ctx, "End flattens.VINSStaticRouteResource", map[string]any{"id": plan.Id.ValueString()})
	return nil
}
