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

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

	diags := diag.Diagnostics{}

	rgListVins, err := utilities.RGListVinsCheckPresence(ctx, state, c)
	if err != nil {
		diags.AddError("Cannot get info about resource group list vins", err.Error())
		return diags
	}

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

	id := uuid.New()
	*state = models.DataSourceRGListVinsModel{
		RGID:      state.RGID,
		Name:      state.Name,
		AccountID: state.AccountID,
		ExtIP:     state.ExtIP,
		VINSID:    state.VINSID,
		SortBy:    state.SortBy,
		Page:      state.Page,
		Size:      state.Size,
		Timeouts:  state.Timeouts,

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

	items := make([]models.ItemsRGListVinsModel, 0, len(rgListVins.Data))
	for _, vinsItem := range rgListVins.Data {
		item := models.ItemsRGListVinsModel{
			AccountID:   types.Int64Value(int64(vinsItem.AccountID)),
			AccountName: types.StringValue(vinsItem.AccountName),
			Computes:    types.Int64Value(int64(vinsItem.Computes)),
			CreatedBy:   types.StringValue(vinsItem.CreatedBy),
			CreatedTime: types.Int64Value(int64(vinsItem.CreatedTime)),
			DeletedBy:   types.StringValue(vinsItem.DeletedBy),
			DeletedTime: types.Int64Value(int64(vinsItem.DeletedTime)),
			ExternalIP:  types.StringValue(vinsItem.ExternalIP),
			ExtnetID:    types.Int64Value(int64(vinsItem.ExtnetId)),
			FreeIPs:     types.Int64Value(int64(vinsItem.FreeIPs)),
			ID:          types.Int64Value(int64(vinsItem.ID)),
			Name:        types.StringValue(vinsItem.Name),
			Network:     types.StringValue(vinsItem.Network),
			PriVNFDevID: types.Int64Value(int64(vinsItem.PriVNFDevID)),
			RGID:        types.Int64Value(int64(vinsItem.RGID)),
			RGName:      types.StringValue(vinsItem.RGName),
			Status:      types.StringValue(vinsItem.Status),
			UpdatedBy:   types.StringValue(vinsItem.UpdatedBy),
			UpdatedTime: types.Int64Value(int64(vinsItem.UpdatedTime)),
		}

		items = append(items, item)
	}

	state.Items = items
	state.EntryCount = types.Int64Value(int64(rgListVins.EntryCount))

	tflog.Info(ctx, "flattens.RGListVinsDataSource: after flatten")

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