package shared

import (
	"context"
	"strconv"

	"velox-bot/internal/db/services"

	"github.com/bwmarrin/discordgo"
)

func RespondEphemeral(s *discordgo.Session, i *discordgo.InteractionCreate, msg string) {
	_ = s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
		Type: discordgo.InteractionResponseChannelMessageWithSource,
		Data: &discordgo.InteractionResponseData{
			Content: msg,
			Flags:   discordgo.MessageFlagsEphemeral,
		},
	})
}

func RequireGuild(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
	if i.GuildID == "" {
		RespondEphemeral(s, i, "This command can only be used in a server.")
		return false
	}
	return true
}

func RequireManageGuild(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
	if i.Member == nil || (i.Member.Permissions&discordgo.PermissionManageGuild) == 0 {
		RespondEphemeral(s, i, "You don't have permission to manage leveling settings.")
		return false
	}
	return true
}

func RequireLevelServices(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
	if services.Global == nil || services.Global.Level == nil || services.Global.LevelSettings == nil {
		RespondEphemeral(s, i, "Leveling service is not available.")
		return false
	}
	return true
}

func RequireLevelSettingsService(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
	if services.Global == nil || services.Global.LevelSettings == nil {
		RespondEphemeral(s, i, "Leveling service is not available.")
		return false
	}
	return true
}

func ParseGuildID(s *discordgo.Session, i *discordgo.InteractionCreate) (int64, bool) {
	guildID, err := strconv.ParseInt(i.GuildID, 10, 64)
	if err != nil {
		RespondEphemeral(s, i, "Invalid guild ID.")
		return 0, false
	}
	return guildID, true
}

func RequireLevelSystemEnabled(s *discordgo.Session, i *discordgo.InteractionCreate) bool {
	if !RequireLevelSettingsService(s, i) {
		return false
	}
	guildID, ok := ParseGuildID(s, i)
	if !ok {
		return false
	}
	enabled, err := services.Global.LevelSettings.IsLevelSystemEnabled(context.Background(), guildID)
	if err != nil {
		RespondEphemeral(s, i, "Failed to load leveling settings.")
		return false
	}
	if !enabled {
		RespondEphemeral(s, i, "Leveling system is disabled on this server. Use /slvl toggle to enable it.")
		return false
	}
	return true
}

func SubcommandOptionMap(i *discordgo.InteractionCreate) map[string]*discordgo.ApplicationCommandInteractionDataOption {
	data := i.ApplicationCommandData()
	if len(data.Options) == 0 {
		return map[string]*discordgo.ApplicationCommandInteractionDataOption{}
	}
	opts := data.Options[0].Options
	m := make(map[string]*discordgo.ApplicationCommandInteractionDataOption, len(opts))
	for _, opt := range opts {
		m[opt.Name] = opt
	}
	return m
}

