package de.viper.survivalplus.commands;

import de.viper.survivalplus.SurvivalPlus;
import de.viper.survivalplus.report.ReportManager;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ReportCommand implements CommandExecutor {

    private final SurvivalPlus plugin;
    private final ReportManager reportManager;

    public ReportCommand(SurvivalPlus plugin, ReportManager reportManager) {
        this.plugin = plugin;
        this.reportManager = reportManager;
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

        if (!(sender instanceof Player player)) {
            sender.sendMessage(plugin.getLangConfig().getString("report.only-players", "§cNur Spieler können diesen Befehl ausführen!"));
            return true;
        }

        if (args.length < 1) {
            player.sendMessage(plugin.getLangConfig().getString("report.usage", "§cVerwendung: /report <Spieler> [Grund]"));
            return true;
        }

        String targetName = args[0];
        String reason = "Kein Grund angegeben";
        if (args.length > 1) {
            reason = String.join(" ", java.util.Arrays.copyOfRange(args, 1, args.length));
        }

        if (Bukkit.getPlayer(targetName) == null) {
            player.sendMessage(plugin.getLangConfig().getString("report.player-not-online", "§cDieser Spieler ist nicht online!"));
            return true;
        }

        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        reportManager.addReport(targetName, player.getName(), reason, time);

        player.sendMessage(plugin.getLangConfig().getString("report.success", "§aDein Report wurde erfolgreich gesendet."));

        // Nachricht an Admins
        String msg = plugin.getLangConfig().getString("report.notify-admin",
            "§cREPORT§r: %reporter% hat %target% gemeldet. Grund: %reason%")
            .replace("%reporter%", player.getName())
            .replace("%target%", targetName)
            .replace("%reason%", reason);
        Bukkit.getOnlinePlayers().stream()
            .filter(p -> p.hasPermission("survivalplus.report.receive"))
            .forEach(p -> p.sendMessage(msg));

        return true;
    }
}
