package telegram_handler

import (
	"context"
	"strconv"
	"strings"
	"ticket-pimp/internal/domain"

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

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

	var (
		taskText string = ""
		answer   string = ""
	)

	msgID := mu.Message.ID
	if mu.Caption != "" {
		taskText = strings.TrimSpace(strings.Replace(mu.Caption, "/task", "", 1))
	} else {
		taskText = strings.TrimSpace(strings.Replace(mu.Text, "/task", "", 1))
	}

	var summaryTail string

	sentances := strings.Split(taskText, "\n")
	if len(sentances) < 2 {
		words := strings.Split(taskText, " ")
		if len(words) > 2 {
			summaryTail = strings.Join(words[0:2], " ")
		} else {
			summaryTail = strings.Join(words, " ")
		}
	} else {
		summaryTail = sentances[0]
	}

	t := domain.NewTask(
		summaryTail,
		taskText,
		mu.From.Username.PeerID(),
		mu.Chat.ID.PeerID(),
	)

	conv, err := h.controller.InitTask(t)

	if err != nil {
		answer := err.Error()
		h.LogMessage(ctx, mu, answer)
		return err
	}

	i := strconv.Itoa(int(conv.ID))
	answer = tg.HTML.Text(
		tg.HTML.Line(
			tg.HTML.Bold("Task ID: "),
			tg.HTML.Code(i),
			tg.HTML.Text(" was created"),
		),
		tg.HTML.Line(
			"Заходи в наш",
			tg.HTML.Link("discord", "https://discord.gg/RHdzK3kUr7"),
			"чтобы отслеживать статус по задаче",
		),
	)
	if mu.Caption != "" {
		answer = tg.HTML.Text(
			tg.HTML.Line(
				tg.HTML.Bold("I'm unable to work with files, but"),
			),
			tg.HTML.Line(
				tg.HTML.Italic(
					tg.HTML.Bold("Task ID: "),
					tg.HTML.Code(i),
					tg.HTML.Text(" was created")),
			),

			tg.HTML.Line(
				"Заходи в наш",
				tg.HTML.Link("discord", "https://discord.gg/RHdzK3kUr7"),
				"чтобы отслеживать статус по задаче",
			),
		)
	}

	h.LogMessage(ctx, mu, answer)
	return mu.Answer(answer).
		ReplyToMessageID(msgID).ParseMode(tg.HTML).DisableWebPagePreview(true).DoVoid(ctx)
}
