import { extractBearerToken } from "../middleware/auth.js";
import { readJsonBody } from "../middleware/body.js";
import { saveToken } from "../../push/device-tokens.js";
export async function handleDeviceToken(req, res) {
    if (req.method !== "POST") {
        res.statusCode = 405;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Method Not Allowed" }));
        return true;
    }
    if (!extractBearerToken(req)) {
        res.statusCode = 401;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Unauthorized: bearer token mismatch" }));
        return true;
    }
    let body;
    try {
        body = await readJsonBody(req);
    }
    catch {
        body = null;
    }
    if (!body) {
        res.statusCode = 400;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "Invalid JSON body" }));
        return true;
    }
    const deviceId = typeof body.deviceId === "string" && body.deviceId.trim() ? body.deviceId.trim() : "";
    const token = typeof body.token === "string" && body.token.trim() ? body.token.trim() : "";
    if (!deviceId || !token) {
        res.statusCode = 400;
        res.setHeader("Content-Type", "application/json");
        res.end(JSON.stringify({ error: "deviceId and token are required" }));
        return true;
    }
    saveToken(deviceId, token);
    res.statusCode = 200;
    res.setHeader("Content-Type", "application/json");
    res.end(JSON.stringify({ ok: true }));
    return true;
}
