//go:generate ${GOBIN}/mockgen -destination jira_mock.go -package=lark ${GO_MODULE}/pkg/clients/lark Interface
package lark

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/spf13/viper"
)

type Interface interface {
	Notify(msgValues interface{}) (string, error)
}

type Client struct {
	notifyAddress string
}

func NewClient() (*Client, error) {
	notifyAddress := viper.GetString("notify-address")
	l := &Client{notifyAddress: notifyAddress}
	return l, nil
}

// send message to end server
func (c *Client) Notify(msgValues interface{}) (string, error) {
	msg, err := json.Marshal(msgValues)
	if err != nil {
		return "", err
	}

	resp, err := http.Post(c.notifyAddress, "application/json", strings.NewReader(string(msg)))
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()
	bodyRaw, err := io.ReadAll(resp.Body)
	if err != nil {
		return "", fmt.Errorf("error when read resp body, %w", err)
	}
	if resp.StatusCode/100 != 2 {
		return "", fmt.Errorf("receive bad status code %d, body is %s", resp.StatusCode, string(bodyRaw))
	}
	var respBody struct {
		MessageIndex string `json:"message_id"`
	}
	err = json.Unmarshal(bodyRaw, &respBody)
	if err != nil {
		return "", fmt.Errorf("unmarshal body error, %w", err)
	}
	return respBody.MessageIndex, nil
}
