#include "mod_quest_loot_share.h"
#include "Config.h"
#include "LootMgr.h"
#include "Player.h"
#include "ScriptMgr.h"

void QuestLootShare::LoadConfig()
{
    _enabled = sConfigMgr->GetOption("QuestLootShare.Enable", true);
}

class QuestLootShare_Player : public PlayerScript
{
public:
    QuestLootShare_Player() : PlayerScript("QuestLootShare_Player", { PLAYERHOOK_ON_BEFORE_FILL_QUEST_LOOT_ITEM }) { }

    // Fires once per group member as the corpse's quest loot is filled for them.
    // Forcing freeforall makes the core treat the item the same way it treats
    // ITEM_FLAG_MULTI_DROP items: looting it only consumes that player's own
    // copy, so every other qualifying member still finds it on the corpse.
    void OnPlayerBeforeFillQuestLootItem(Player* /*player*/, LootItem& item) override
    {
        if (!sQuestLootShare->IsEnabled())
            return;

        item.freeforall = true;
    }
};

class QuestLootShare_World : public WorldScript
{
public:
    QuestLootShare_World() : WorldScript("QuestLootShare_World") { }

    void OnBeforeConfigLoad(bool /*reload*/) override
    {
        sQuestLootShare->LoadConfig();
    }
};

void AddSC_mod_quest_loot_share()
{
    new QuestLootShare_Player();
    new QuestLootShare_World();
}