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

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

	diags := diag.Diagnostics{}

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

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

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

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

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

	items := make([]models.ItemIPVinsModel, 0, len(ipList.Data))
	for _, item := range ipList.Data {
		ip := models.ItemIPVinsModel{
			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)),
		}
		items = append(items, ip)
	}
	state.Items = items

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