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/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"
)

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

	diags := diag.Diagnostics{}

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

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

	tflog.Info(ctx, "flattens.VINSExtNetListDataSource: before flatten", map[string]any{"vins_id": vinsId})

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

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

	items := make([]models.ItemExtNetVinsModel, 0, len(extnetList.Data))
	for _, item := range extnetList.Data {
		en := models.ItemExtNetVinsModel{
			DefaultGW:  types.StringValue(item.DefaultGW),
			ExtNetID:   types.Int64Value(int64(item.ExtNetID)),
			IP:         types.StringValue(item.IP),
			PrefixLen:  types.Int64Value(int64(item.PrefixLen)),
			Status:     types.StringValue(item.Status),
			TechStatus: types.StringValue(item.TechStatus),
		}
		items = append(items, en)
	}
	state.Items = items

	tflog.Info(ctx, "End flattens.VINSExtNetListDataSource", map[string]any{"vins_id": state.Id.ValueString()})
	return nil
}
