package tmi

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

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

type ExtensionMessage struct {
	ExtensionClientID string `json:"extension_client_id"`
	ExtensionName     string `json:"extension_name"`
	ExtensionVersion  string `json:"extension_version"`
	ChannelID         string `json:"channel_id"`
	Body              string `json:"body"`
	IsPinned          bool   `json:"is_pinned"`
}

func (c *clientImpl) SendExtensionMessage(ctx context.Context, message ExtensionMessage, reqOpts *twitchclient.ReqOpts) error {
	url := "/internal/extension_message"
	bodyBytes, err := json.Marshal(message)
	if err != nil {
		return err
	}

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

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

	resp, err := c.Do(ctx, req, combinedReqOpts)
	if err != nil {
		return err
	}

	defer closeBody(resp)

	if resp.StatusCode == http.StatusNoContent {
		return httpErrorImpl{
			err:        err,
			statusCode: resp.StatusCode,
		}
	} else if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("unexpected response code %d during call to SendExtensionMessage", resp.StatusCode)
	}
	return nil
}
