//go:build e2e

package client

import (
	"context"
	"fmt"
	"net/url"
)

// AppMessage is a message row returned by the messages API.
type AppMessage struct {
	ID        string `json:"id"`
	ChannelID string `json:"channelId"`
	Content   string `json:"content"`
	SenderID  string `json:"senderId"`
}

// AppMessagePage is a paginated channel message list.
type AppMessagePage struct {
	Messages []AppMessage `json:"messages"`
}

// CreateMessage posts a human-authored message to a channel or DM scope.
func (c *Client) CreateMessage(ctx context.Context, scopeID, content string) (AppMessage, int, []byte, error) {
	req := map[string]any{
		"scopeId": scopeID,
		"content": content,
	}
	var out AppMessage
	status, raw, err := c.DoJSON(ctx, "POST", scopeMessagesPath(c.workspace, scopeID), req, &out)
	return out, status, raw, err
}

// ListChannelMessages returns recent messages for a channel or DM scope.
func (c *Client) ListChannelMessages(ctx context.Context, channelID string, limit int) (AppMessagePage, int, []byte, error) {
	if limit <= 0 {
		limit = 50
	}
	var out AppMessagePage
	path := fmt.Sprintf("%s?limit=%d", scopeMessagesPath(c.workspace, channelID), limit)
	status, raw, err := c.DoJSON(ctx, "GET", path, nil, &out)
	return out, status, raw, err
}

func scopeMessagesPath(workspaceID string, scopeID string) string {
	return fmt.Sprintf(
		"/api/v1/workspaces/%s/scopes/%s/messages",
		url.PathEscape(workspaceID),
		url.PathEscape(scopeID),
	)
}
