package telegram

import (
	"context"
	"log"
	"ticket-pimp/client/telegram/telegram_handler"
	"ticket-pimp/internal/controller"
	"ticket-pimp/internal/domain"
	"ticket-pimp/internal/external"

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

type TelegramOptions struct {
	GitService   *external.Git
	CloudService *external.Cloud
	Coda         *external.Coda
	AppConfig    *domain.Config
	Controller   *controller.WorkflowController
}

// runTgBot ...
// ..function creates new Telegram BOT instance
// ..throw env variables through bot's handlers
// ..setup tg bot router;
// and finally returns tgb.Poller
func Run(ctx context.Context, opts TelegramOptions) error {

	log.Print("Start telegram bot init..")
	client := tg.New(opts.AppConfig.Telegram.Token)

	h := telegram_handler.NewHandler(
		opts.GitService,
		opts.CloudService,
		opts.Coda,
		opts.Controller,
	)

	router := tgb.NewRouter().
		Message(h.Init, tgb.Command("init")).
		Message(h.PingHandler, tgb.Command("ping")).
		// Message(h.DevelopmentTaskHandler, tgb.TextHasPrefix("/new")).
		// Message(h.NewRepoHandler, tgb.TextHasPrefix("/repo")).
		// Message(h.NewFolderHandler, tgb.TextHasPrefix("/folder")).
		Message(h.FarmTaskHandler, tgb.TextHasPrefix("/task"))

	log.Print("Success init. Start poller.")
	return tgb.NewPoller(
		router,
		client,
	).Run(ctx)
}
