// NO definir MINIAUDIO_IMPLEMENTATION aqui — vive en audio_engine.cpp.
#include "../../vendor/miniaudio/miniaudio.h"

#include "audio_play.h"

#include <cstdlib>

namespace fn::audio {

Sound sound_load(Engine& e, const char* path) {
    Sound s{nullptr, false};
    if (!e.ok || !e.impl || !path) return s;
    ma_sound* snd = static_cast<ma_sound*>(std::malloc(sizeof(ma_sound)));
    if (!snd) return s;
    ma_engine* eng = static_cast<ma_engine*>(e.impl);
    if (ma_sound_init_from_file(eng, path, 0, NULL, NULL, snd) != MA_SUCCESS) {
        std::free(snd);
        return s;
    }
    s.impl = snd;
    s.ok   = true;
    return s;
}

void sound_play(Sound& s) {
    if (!s.ok || !s.impl) return;
    ma_sound_start(static_cast<ma_sound*>(s.impl));
}

void sound_stop(Sound& s) {
    if (!s.ok || !s.impl) return;
    ma_sound_stop(static_cast<ma_sound*>(s.impl));
}

void sound_set_volume(Sound& s, float v) {
    if (!s.ok || !s.impl) return;
    ma_sound_set_volume(static_cast<ma_sound*>(s.impl), v);
}

void sound_destroy(Sound& s) {
    if (!s.ok || !s.impl) return;
    ma_sound* snd = static_cast<ma_sound*>(s.impl);
    ma_sound_uninit(snd);
    std::free(snd);
    s.impl = nullptr;
    s.ok   = false;
}

void play_sound_oneshot(Engine& e, const char* path, float volume) {
    if (!e.ok || !e.impl || !path) return;
    ma_engine* eng = static_cast<ma_engine*>(e.impl);
    // ma_engine_play_sound respeta el master volume; volume per-call se aplica
    // creando un sonido ad-hoc si el caller quiere control fino. Para fire-and-forget
    // usamos el helper directo y dejamos el master modular.
    (void)volume;
    ma_engine_play_sound(eng, path, NULL);
}

}  // namespace fn::audio
