package screens

import (
	tea "charm.land/bubbletea/v2"

	"git.secluded.site/keld/internal/ui"
)

// drain feeds commands back into a screen until a DoneMsg or BackMsg
// is produced, or the command chain is exhausted. This is necessary
// because huh uses internal message chains (nextFieldMsg →
// nextGroupMsg → StateCompleted) that must be processed sequentially.
func drain[S ui.Screen](s S, initialCmd tea.Cmd) (S, tea.Cmd) {
	cmd := initialCmd
	for cmd != nil {
		msg := cmd()
		if msg == nil {
			return s, nil
		}
		switch msg.(type) {
		case ui.DoneMsg:
			return s, cmd
		case ui.BackMsg:
			return s, cmd
		}
		var screen ui.Screen
		screen, cmd = s.Update(msg)
		s = screen.(S)
	}
	return s, nil
}
