package tmi

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/url"

	"code.justin.tv/foundation/twitchclient"
)

// DeleteChatMessageRequest is the request params for DeleteChatMessage
type DeleteChatMessageRequest struct {
	MessageID   string `json:"message_id"`
	ChannelID   string `json:"channel_id"`
	RequesterID string `json:"requester_id"`
}

// DeleteChatMessageResponse is the JSON response from DeleteChatMessage
type DeleteChatMessageResponse struct {
	ResponseCode string       `json:"response_code"`
	Message      *ChatMessage `json:"message"`
}

// DeleteChatMessage deletes a single chat message from stream chat
func (c *clientImpl) DeleteChatMessage(ctx context.Context, params DeleteChatMessageRequest, reqOpts *twitchclient.ReqOpts) (DeleteChatMessageResponse, error) {
	path := fmt.Sprintf("/rooms/%s/message/%s", url.QueryEscape(params.ChannelID), url.QueryEscape(params.MessageID))

	bodyBytes, err := json.Marshal(params)
	if err != nil {
		return DeleteChatMessageResponse{}, err
	}

	req, err := c.NewRequest("DELETE", path, bytes.NewReader(bodyBytes))
	if err != nil {
		return DeleteChatMessageResponse{}, err
	}

	combinedReqOpts := twitchclient.MergeReqOpts(reqOpts, twitchclient.ReqOpts{
		StatName:       "service.clue.delete_chat_message",
		StatSampleRate: defaultStatSampleRate,
	})

	var response DeleteChatMessageResponse
	if _, err := c.DoJSON(ctx, &response, req, combinedReqOpts); err != nil {
		return DeleteChatMessageResponse{}, err
	}
	return response, nil
}
