package app

import (
	"encoding/base64"
	"net/url"
	"strings"
)

type agentDirectoryCursor struct {
	DisplayName string
	AgentID     string
}

func encodeAgentDirectoryCursor(cursor agentDirectoryCursor) (string, error) {
	normalized, err := normalizeAgentDirectoryCursor(cursor)
	if err != nil {
		return "", err
	}
	values := url.Values{}
	values.Set("displayName", normalized.DisplayName)
	values.Set("agentId", normalized.AgentID)
	return base64.RawURLEncoding.EncodeToString([]byte(values.Encode())), nil
}

func decodeAgentDirectoryCursor(token string) (agentDirectoryCursor, error) {
	trimmed := strings.TrimSpace(token)
	if trimmed == "" {
		return agentDirectoryCursor{}, nil
	}
	payload, err := base64.RawURLEncoding.DecodeString(trimmed)
	if err != nil {
		return agentDirectoryCursor{}, badRequest("invalid agent directory cursor")
	}
	values, err := url.ParseQuery(string(payload))
	if err != nil {
		return agentDirectoryCursor{}, badRequest("invalid agent directory cursor")
	}
	return normalizeAgentDirectoryCursor(agentDirectoryCursor{
		DisplayName: values.Get("displayName"),
		AgentID:     values.Get("agentId"),
	})
}

func normalizeAgentDirectoryCursor(cursor agentDirectoryCursor) (agentDirectoryCursor, error) {
	trimmedAgentID := strings.TrimSpace(cursor.AgentID)
	if trimmedAgentID == "" {
		return agentDirectoryCursor{}, badRequest("invalid agent directory cursor")
	}
	return agentDirectoryCursor{
		DisplayName: strings.TrimSpace(cursor.DisplayName),
		AgentID:     trimmedAgentID,
	}, nil
}
