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

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

	diags := diag.Diagnostics{}

	extNetReservationIP, err := utilities.ExtNetReservedIPCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Cannot get info about extnet reserved ip list", err.Error())
		return diags
	}

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

	id := uuid.New()
	*state = models.DataSourceExtNetReservedIPModel{
		AccountID: state.AccountID,
		ExtNetID:  state.ExtNetID,
		Timeouts:  state.Timeouts,

		Id: types.StringValue(id.String()),
	}

	items := make([]models.ItemReservedIPModel, 0, len(extNetReservationIP))
	for _, item := range extNetReservationIP {
		i := models.ItemReservedIPModel{
			ExtNetID:     types.Int64Value(int64(item.ExtnetID)),
			Reservations: flattenReservations(ctx, item.Reservations),
		}
		items = append(items, i)
	}
	state.Items = items

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

func flattenReservations(ctx context.Context, reservations []extnet.Reservations) []models.ItemReservationsModel {
	tflog.Info(ctx, "Start flattenReservations")
	tempSlice := make([]models.ItemReservationsModel, 0, len(reservations))
	for _, item := range reservations {
		res := models.ItemReservationsModel{
			AccountID:  types.Int64Value(int64(item.AccountID)),
			ClientType: types.StringValue(item.ClientType),
			DomainName: types.StringValue(item.DomainName),
			HostName:   types.StringValue(item.Hostname),
			IP:         types.StringValue(item.IP),
			MAC:        types.StringValue(item.Mac),
			Type:       types.StringValue(item.Type),
			VMID:       types.Int64Value(int64(item.VMID)),
		}
		tempSlice = append(tempSlice, res)
	}

	tflog.Info(ctx, "End flattenReservations")
	return tempSlice
}
