package main

import (
	"flag"
	"github.com/bwmarrin/discordgo"
	"github.com/joho/godotenv"
	"kleincordBot/commands"
	"kleincordBot/handlers"
	"kleincordBot/routers"
	"kleincordBot/services"
	"log"
	"os"
	"os/signal"
	"time"
)

var GuildID = flag.String("guild", "", "Test guild ID. If not passed - bot registers commands globally")

func main() {
	flag.Parse()
	err := godotenv.Load()
	if err != nil {
		log.Fatalf(".env not found: %v", err)
		return
	}
	handlers.LogChannelID = os.Getenv("LOG_CHANNEL_ID")

	services.InitServers()

	discord, err := discordgo.New("Bot " + os.Getenv("BOT_TOKEN"))
	if err != nil {
		log.Fatalf(err.Error())
	}

	discord.AddHandler(routers.MessageRouter)
	discord.AddHandler(routers.CommandRouter)

	err = discord.Open()
	if err != nil {
		log.Fatalf("Cannot open the session: %v", err)
	} else {
		discord.ChannelMessageSendEmbed(
			handlers.LogChannelID,
			&discordgo.MessageEmbed{
				Title:     "started " + os.Getenv("ENVIRONMENT"),
				Timestamp: time.Now().Format(time.RFC3339),
			})
	}

	_, err = discord.ApplicationCommandBulkOverwrite(discord.State.User.ID, *GuildID, commands.Commands)
	if err != nil {
		print(err.Error())
	}

	defer discord.Close()

	stop := make(chan os.Signal, 1)
	signal.Notify(stop, os.Interrupt)
	log.Println("Press Ctrl+C to exit")
	<-stop
}
