package handler

import (
	"context"
	"errors"
	"strconv"
	"strings"

	"github.com/mr-linch/go-tg"
	"github.com/mr-linch/go-tg/tgb"
)

func (h *Handler) DevelopmentTaskHandler(ctx context.Context, mu *tgb.MessageUpdate) error {

	str := strings.Replace(mu.Text, "/new", "", 1)

	if str == "" {
		return errors.New("empty command provided")
	}

	issueKeyStr, err := h.workflow.Workflow(str, h.key, h.id)

	if err != nil {
		answer := errorAnswer(err.Error())
		h.LogMessage(ctx, mu, answer)
		return mu.Answer(answer).ParseMode(tg.HTML).DoVoid(ctx)
	}

	i, err := strconv.Atoi(h.id)
	if err != nil {
		return errors.New("problem with conversion id to int")
	}
	h.id = strconv.Itoa(i + 1)

	answer := newTicketAnswer(issueKeyStr)
	h.LogMessage(ctx, mu, answer)
	return mu.Answer(answer).ParseMode(tg.HTML).DoVoid(ctx)
}

func newTicketAnswer(name string) string {
	return tg.HTML.Text(
		tg.HTML.Line(
			"🤘 Ticket ",
			name,
			" has been created!",
		),
	)
}
