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

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

	diags := diag.Diagnostics{}

	vinsList, diags := utilities.VINSListDeletedDataSourceCheckPresence(ctx, state, c)
	if diags.HasError() {
		return diags
	}

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

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

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

	items := make([]models.ItemVinsDeletedModel, 0, len(vinsList.Data))
	for _, item := range vinsList.Data {
		v := models.ItemVinsDeletedModel{
			AccountID:   types.Int64Value(int64(item.AccountID)),
			AccountName: types.StringValue(item.AccountName),
			CreatedBy:   types.StringValue(item.CreatedBy),
			CreatedTime: types.Int64Value(int64(item.CreatedTime)),
			DeletedBy:   types.StringValue(item.DeletedBy),
			DeletedTime: types.Int64Value(int64(item.DeletedTime)),
			ExternalIP:  types.StringValue(item.ExternalIP),
			ID:          types.Int64Value(int64(item.ID)),
			Name:        types.StringValue(item.Name),
			Network:     types.StringValue(item.Network),
			RGID:        types.Int64Value(int64(item.RGID)),
			RGName:      types.StringValue(item.RGName),
			Status:      types.StringValue(item.Status),
			UpdatedBy:   types.StringValue(item.UpdatedBy),
			UpdatedTime: types.Int64Value(int64(item.UpdatedTime)),
			VXLANID:     types.Int64Value(int64(item.VXLANID)),
		}
		items = append(items, v)
	}
	state.Items = items

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