//go:build e2e

package client

import (
	"context"
	"fmt"
)

// Channel is a workspace channel row.
type Channel struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Slug        string `json:"slug"`
	DisplayName string `json:"displayName"`
	Description string `json:"description"`
	Joined      bool   `json:"joined"`
}

// DMChannel is a direct-message channel between two workspace members.
type DMChannel struct {
	ID       string `json:"id"`
	PeerType string `json:"peerType"`
	PeerID   string `json:"peerId"`
	PeerName string `json:"peerName"`
}

// ReplyThreadSummary is returned when opening a reply thread.
type ReplyThreadSummary struct {
	ThreadChannelID string `json:"threadChannelId"`
	ReplyCount      int64  `json:"replyCount"`
}

// ListChannels returns channels visible to the authenticated user.
func (c *Client) ListChannels(ctx context.Context) ([]Channel, int, []byte, error) {
	var out []Channel
	path := fmt.Sprintf("/api/v1/workspaces/%s/channels", c.workspace)
	status, raw, err := c.DoJSON(ctx, "GET", path, nil, &out)
	return out, status, raw, err
}

// CreateChannel creates a workspace channel.
func (c *Client) CreateChannel(ctx context.Context, name, description string) (Channel, int, []byte, error) {
	req := map[string]string{
		"name":        name,
		"description": description,
	}
	var out Channel
	path := fmt.Sprintf("/api/v1/workspaces/%s/channels", c.workspace)
	status, raw, err := c.DoJSON(ctx, "POST", path, req, &out)
	return out, status, raw, err
}

// OpenDMWithUser opens or creates a human DM channel with another user.
func (c *Client) OpenDMWithUser(ctx context.Context, peerUserID string) (DMChannel, int, []byte, error) {
	req := map[string]string{"userId": peerUserID}
	var out DMChannel
	path := fmt.Sprintf("/api/v1/workspaces/%s/channels/dm", c.workspace)
	status, raw, err := c.DoJSON(ctx, "POST", path, req, &out)
	return out, status, raw, err
}

// OpenReplyThread opens or resolves a reply thread for a parent channel message.
func (c *Client) OpenReplyThread(ctx context.Context, channelID, parentMessageID string) (ReplyThreadSummary, int, []byte, error) {
	req := map[string]string{"parentMessageId": parentMessageID}
	var out ReplyThreadSummary
	path := fmt.Sprintf("/api/v1/workspaces/%s/channels/%s/threads", c.workspace, channelID)
	status, raw, err := c.DoJSON(ctx, "POST", path, req, &out)
	return out, status, raw, err
}

// AddChannelUserMember adds a human user to a channel.
func (c *Client) AddChannelUserMember(ctx context.Context, channelID, userID string) (int, []byte, error) {
	req := map[string]string{"userId": userID}
	path := fmt.Sprintf("/api/v1/workspaces/%s/channels/%s/members", c.workspace, channelID)
	return c.DoJSON(ctx, "POST", path, req, nil)
}
