package events

import (
	"context"
	"log"
	"strconv"
	"strings"
	"velox-bot/internal/db/services"

	"github.com/bwmarrin/discordgo"
)

func HandleMessageCreate(s *discordgo.Session, m *discordgo.MessageCreate, services *services.Services) {
	if m.Author.Bot || m.GuildID == "" {
		return
	}
	ctx := context.Background()
	guildID := mustParseInt64(m.GuildID)
	userID := mustParseInt64(m.Author.ID)
	res, err := services.Level.HandleMessage(ctx, guildID, userID)
	if err != nil || !res.LeveledUp {
		return
	}
	// Decide where to send the level-up message
	targetChannelID := m.ChannelID
	if res.LevelupChannel != 0 {
		targetChannelID = strconv.FormatInt(res.LevelupChannel, 10)
	}
	content, err := services.LevelSettings.GetLevelUpMessage(ctx, guildID)
	if err != nil {
		return
	}
	content = strings.ReplaceAll(content, "{user}", m.Author.Mention())
	content = strings.ReplaceAll(content, "{level}", strconv.Itoa(res.NewLevel))

	s.ChannelMessageSend(targetChannelID, content)
	// Apply role reward if any
	if res.RoleRewardID != 0 {
		roleID := strconv.FormatInt(res.RoleRewardID, 10)
		if err := s.GuildMemberRoleAdd(m.GuildID, m.Author.ID, roleID); err != nil {
			log.Printf("Failed to add role reward: guild=%s user=%s role=%s err=%v", m.GuildID, m.Author.ID, roleID, err)
		}
	}
}

func mustParseInt64(s string) int64 {
	id, _ := strconv.ParseInt(s, 10, 64)
	return id
}
