package tmi

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"

	"code.justin.tv/foundation/twitchclient"

	"context"
)

// ChatRestrictedReasons returns a list of reasons that a user would not be able to chat in a channel
// If the user can chat regardless of chat mode (for example, broadcasters or moderators), the list will be empty
func (c *clientImpl) ChatRestrictedReasons(ctx context.Context, params ChatRestrictedReasonsParams, reqOpts *twitchclient.ReqOpts) (ChatRestrictedReasonsResponse, error) {
	path := fmt.Sprintf("/internal/users/%s/chat_restricted_reasons/%s", url.PathEscape(params.UserID), url.PathEscape(params.ChannelID))
	req, err := c.NewRequest("GET", path, nil)
	if err != nil {
		return ChatRestrictedReasonsResponse{}, err
	}

	combinedReqOpts := twitchclient.MergeReqOpts(reqOpts, twitchclient.ReqOpts{
		StatName:       "service.clue.chat_restricted_reasons",
		StatSampleRate: defaultStatSampleRate,
	})
	resp, err := c.Do(ctx, req, combinedReqOpts)
	if err != nil {
		return ChatRestrictedReasonsResponse{}, err
	}

	defer closeBody(resp)

	if resp.StatusCode != http.StatusOK {
		return ChatRestrictedReasonsResponse{}, httpErrorImpl{
			statusCode: resp.StatusCode,
		}
	}

	var decoded ChatRestrictedReasonsResponse
	if err := json.NewDecoder(resp.Body).Decode(&decoded); err != nil {
		return ChatRestrictedReasonsResponse{}, err
	}
	return decoded, nil
}

type ChatRestrictedReasonsParams struct {
	UserID    string
	ChannelID string
}

type ChatRestrictedReasonsResponse struct {
	Reasons []string `json:"reasons"`
}

const (
	ChatRestrictedReasonFollowersOnly   = "followers_only"
	ChatRestrictedReasonSubscribersOnly = "subs_only"
	ChatRestrictedReasonVerifiedOnly    = "verified_only"
	ChatRestrictedReasonSlowMode        = "slow_mode"
)
