import fs from "node:fs";
import webpush from "web-push";

const [inputPath, outputPath] = process.argv.slice(2);

if (!inputPath || !outputPath) {
  throw new Error("Expected input and output file paths.");
}

const batch = JSON.parse(fs.readFileSync(inputPath, "utf8"));
webpush.setVapidDetails(
  batch.vapid.subject,
  batch.vapid.publicKey,
  batch.vapid.privateKey,
);

const result = {
  queued: Array.isArray(batch.subscriptions) ? batch.subscriptions.length : 0,
  success: 0,
  failed: 0,
  failures: [],
};

for (const subscription of batch.subscriptions || []) {
  try {
    await webpush.sendNotification(
      {
        endpoint: subscription.endpoint,
        expirationTime: null,
        keys: {
          p256dh: subscription.publicKey,
          auth: subscription.authToken,
        },
      },
      JSON.stringify(batch.payload),
      {
        TTL: 900,
        urgency: "normal",
        contentEncoding: subscription.contentEncoding || "aesgcm",
      },
    );
    result.success += 1;
  } catch (error) {
    result.failed += 1;
    result.failures.push({
      endpoint: subscription.endpoint,
      reason:
        error?.body || error?.message || error?.toString() || "Delivery failed",
    });
  }
}

fs.writeFileSync(outputPath, `${JSON.stringify(result)}\n`);
