package flattens

import (
	"context"
	"fmt"

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

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

	diags := diag.Diagnostics{}

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

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

	id := uuid.New()
	*state = models.DataSourceRGListDeletedModel{
		ById:          state.ById,
		Name:          state.Name,
		AccountId:     state.AccountId,
		AccountName:   state.AccountName,
		CreatedAfter:  state.CreatedAfter,
		CreatedBefore: state.CreatedBefore,
		LockStatus:    state.LockStatus,
		SortBy:        state.SortBy,
		Page:          state.Page,
		Size:          state.Size,
		Timeouts:      state.Timeouts,

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

	items := make([]models.ItemsRGListDeletedModel, 0, len(rgList.Data))
	for _, rgItem := range rgList.Data {
		item := models.ItemsRGListDeletedModel{
			AccountACL:             flattenACL(ctx, &rgItem.ACL),
			AccountID:              types.Int64Value(int64(rgItem.AccountID)),
			AccountName:            types.StringValue(rgItem.AccountName),
			CPUAllocationParameter: types.StringValue(rgItem.CPUAllocationParameter),
			CPUAllocationRatio:     types.Float64Value(rgItem.CPUAllocationRatio),
			CreatedBy:              types.StringValue(rgItem.CreatedBy),
			CreatedTime:            types.Int64Value(int64(rgItem.CreatedTime)),
			DefNetID:               types.Int64Value(rgItem.DefNetID),
			DefNetType:             types.StringValue(rgItem.DefNetType),
			DeletedBy:              types.StringValue(rgItem.DeletedBy),
			DeletedTime:            types.Int64Value(int64(rgItem.DeletedTime)),
			Description:            types.StringValue(rgItem.Description),
			Dirty:                  types.BoolValue(rgItem.Dirty),
			GID:                    types.Int64Value(int64(rgItem.GID)),
			GUID:                   types.Int64Value(int64(rgItem.GUID)),
			RGID:                   types.Int64Value(int64(rgItem.ID)),
			LockStatus:             types.StringValue(rgItem.LockStatus),
			Milestones:             types.Int64Value(int64(rgItem.Milestones)),
			Name:                   types.StringValue(rgItem.Name),
			ResourceLimits: &models.ResourceLimitsModel{
				CUC:      types.Float64Value(rgItem.ResourceLimits.CUC),
				CUD:      types.Float64Value(rgItem.ResourceLimits.CUD),
				CUDM:     types.Float64Value(rgItem.ResourceLimits.CUDM),
				CUI:      types.Float64Value(rgItem.ResourceLimits.CUI),
				CUM:      types.Float64Value(rgItem.ResourceLimits.CUM),
				CUNP:     types.Float64Value(rgItem.ResourceLimits.CUNP),
				GPUUnits: types.Float64Value(rgItem.ResourceLimits.GPUUnits),
			},
			Secret:      types.StringValue(rgItem.Secret),
			Status:      types.StringValue(rgItem.Status),
			UpdatedBy:   types.StringValue(rgItem.UpdatedBy),
			UpdatedTime: types.Int64Value(int64(rgItem.UpdatedTime)),
		}

		var diagsItem diag.Diagnostics
		item.UniqPools, diagsItem = types.ListValueFrom(ctx, types.StringType, rgItem.UniqPools)
		if diagsItem.HasError() {
			tflog.Error(ctx, fmt.Sprint("flattens.RGListDeletedDataSource: cannot flatten rgItem.UniqPools to item.UniqPools", diags))
		}
		item.VINS, diagsItem = types.ListValueFrom(ctx, types.Int64Type, rgItem.VINS)
		if diagsItem.HasError() {
			tflog.Error(ctx, fmt.Sprint("flattens.RGListDeletedDataSource: cannot flatten rgItem.VINS to item.VINS", diags))
		}
		item.ResTypes, diagsItem = types.ListValueFrom(ctx, types.StringType, rgItem.ResTypes)
		if diagsItem.HasError() {
			tflog.Error(ctx, fmt.Sprint("flattens.RGListDeletedDataSource: cannot flatten rgItem.ResTypes to item.ResTypes", diags))
		}
		item.VMS, diagsItem = types.ListValueFrom(ctx, types.Int64Type, rgItem.Computes)
		if diagsItem.HasError() {
			tflog.Error(ctx, fmt.Sprint("flattens.RGListDeletedDataSource: cannot flatten rgItem.Computes to item.Computes", diags))
		}
		item.ComputeFeatures, diagsItem = types.ListValueFrom(ctx, types.StringType, rgItem.ComputeFeatures)
		if diagsItem.HasError() {
			tflog.Error(ctx, fmt.Sprint("flattens.RGListDeletedDataSource: cannot flatten rgItem.ComputeFeatures to item.ComputeFeatures", diags))
		}

		items = append(items, item)
	}

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

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

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