//nolint:dupl // temporary disabled
package tablebuilder

import (
	"sort"

	"github.com/bartosian/suimon/internal/core/domain/enums"
	domainhost "github.com/bartosian/suimon/internal/core/domain/host"
	"github.com/bartosian/suimon/internal/core/domain/service/tablebuilder/tables"
)

// handleValidatorTable handles the configuration for the Validator table.
func (tb *Builder) handleValidatorTable(hosts []domainhost.Host) error {
	tableConfig := tables.NewDefaultTableConfig(enums.TableTypeValidator)

	sort.SliceStable(hosts, func(i, j int) bool {
		left, right := hosts[i], hosts[j]
		if left.Status != right.Status {
			return left.Status > right.Status
		}

		if left.Metrics.LastCommittedLeaderRound != right.Metrics.LastCommittedLeaderRound {
			return left.Metrics.LastCommittedLeaderRound > right.Metrics.LastCommittedLeaderRound
		}

		return left.Metrics.HighestSyncedCheckpoint > right.Metrics.HighestSyncedCheckpoint
	})

	for idx := range hosts {
		host := hosts[idx]

		if !host.Metrics.Updated {
			continue
		}

		columnValues := tables.GetValidatorColumnValues(idx, &host)

		tableConfig.Columns.SetColumnValues(columnValues)

		tableConfig.RowsCount++
	}

	tb.config = tableConfig

	return nil
}
