package handler

import (
	"context"
	"fmt"
	"log"
	"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 {

	msgID := mu.Message.ID

	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(),
	)

	id, err := h.coda.CreateTask(t.Summary, t.Description, t.Creator, t.CreatorLink)
	if err != nil {
		answer := errorAnswer(err.Error())
		h.LogMessage(ctx, mu, answer)
		return mu.Answer(answer).ParseMode(tg.HTML).DoVoid(ctx)
	}
	if id == "" {
		answer := errorAnswer("task wasn't created")
		h.LogMessage(ctx, mu, answer)
		return mu.Answer(answer).ParseMode(tg.HTML).DoVoid(ctx)
	}

	err = mu.Answer(fmt.Sprintf("Задача с id: %s была создана, жду ссылку", id)).DoVoid(ctx)
	if err != nil {
		log.Println("бот не смог ответить про создание задачи")
	}

	url, err := h.coda.GetRowLink(id)
	if err != nil {
		answer := err.Error()
		h.LogMessage(ctx, mu, answer)
		return err
	}
	t.URL = url

	answer := tg.HTML.Text(
		tg.HTML.Line(tg.HTML.Link("🤘 Задача", t.URL), "была создана!"))
	h.LogMessage(ctx, mu, answer)
	return mu.Answer(answer).
		ReplyToMessageID(msgID).ParseMode(tg.HTML).DisableWebPagePreview(true).DoVoid(ctx)
}
