import { apiFetch } from "../../net/api";
import { useAppStore } from "../../store";
import { t } from "../../i18n";

// One-shot text-only message between same-user devices. Reuses the SSE Hub
// the same way the file-transfer signaling channel does (POST /api/message).
// No DB persistence; the receiver-side store keeps it in memory only.
export async function sendMessage(receiverName: string, text: string): Promise<void>
{
    const trimmed = text.trim();
    if (!trimmed) { throw new Error(t("errors.messageEmpty")); }
    if (trimmed.length > 4096)
    {
        throw new Error(t("errors.messageOverflow"));
    }
    if (!receiverName) { throw new Error(t("errors.noReceiver")); }

    const r = await apiFetch("/api/message", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ to: receiverName, text: trimmed }),
    });
    if (!r.ok)
    {
        const text = await r.text().catch(() => r.statusText);
        throw new Error(`message ${r.status}: ${text}`);
    }

    useAppStore.getState().addMessage({
        id: crypto.randomUUID(),
        direction: "outgoing",
        peerName: receiverName,
        text: trimmed,
        sentAt: Math.floor(Date.now() / 1000),
    });
}
