package api

import (
	"strings"

	"github.com/tidbcloud/AgentTeam/desktop/internal/profile"
	"github.com/tidbcloud/AgentTeam/desktop/internal/types"
	"github.com/tidbcloud/AgentTeam/desktop/internal/userauth"
)

type desktopServerTargets struct {
	persisted *profile.ServerManager
	userAuth  *userauth.Manager
}

type electronActiveTargetHistory struct {
	manager *userauth.Manager
}

func (history electronActiveTargetHistory) LastActiveTarget() (string, bool) {
	if history.manager == nil {
		return "", false
	}
	targetID, ok := history.manager.LastActiveTarget()
	if !ok {
		return "", false
	}
	if _, ok := history.manager.Target(targetID); !ok {
		return "", false
	}
	return targetID, true
}

func (history electronActiveTargetHistory) SetLastActiveTarget(targetID string) error {
	if history.manager == nil {
		return nil
	}
	return history.manager.SetLastActiveTarget(targetID)
}

func (history electronActiveTargetHistory) ClearLastActiveTarget(targetID string) error {
	if history.manager == nil {
		return nil
	}
	return history.manager.ClearLastActiveTarget(targetID)
}

func (targets desktopServerTargets) Get(id string) (profile.AgentTeamServer, bool) {
	if targets.userAuth != nil {
		if server, ok := targets.userAuth.Get(id); ok {
			if targets.persisted != nil {
				server.MachineID = matchingMachineID(targets.persisted.All(), server)
			}
			return server, true
		}
	}
	if targets.persisted == nil {
		return profile.AgentTeamServer{}, false
	}
	return targets.persisted.Get(id)
}

func matchingMachineID(servers []profile.AgentTeamServer, target profile.AgentTeamServer) string {
	targetURL := strings.TrimRight(strings.TrimSpace(target.ServerURL), "/")
	targetWorkspaceID := strings.TrimSpace(target.WorkspaceID)
	for _, server := range servers {
		if !server.Enabled ||
			strings.TrimRight(strings.TrimSpace(server.ServerURL), "/") != targetURL ||
			strings.TrimSpace(server.WorkspaceID) != targetWorkspaceID {
			continue
		}
		if machineID := strings.TrimSpace(server.MachineID); machineID != "" {
			return machineID
		}
	}
	return ""
}

func (targets desktopServerTargets) ServerAvailableForSelection(id string) bool {
	if targets.userAuth != nil && targets.userAuth.ServerAvailableForSelection(id) {
		return true
	}
	return targets.persisted != nil && targets.persisted.ServerAvailableForSelection(id)
}

func gatewayConnection(
	connections types.ServerConnectionAccessor,
	userAuth *userauth.Manager,
	id string,
) (types.ServerConnection, bool) {
	if userAuth != nil {
		if connection, ok := userAuth.Connection(id); ok {
			return connection, true
		}
	}
	if connections == nil {
		return nil, false
	}
	return connections.ServerConnection(id)
}
