import { Router } from "express";
import type { Db } from "@paperclipai/db";
import { getVapidPublicKey, saveSubscription, removeSubscription } from "../services/pushService.js";

export function pushRoutes(db: Db): Router {
  const router = Router();

  // GET /api/push/vapid-public-key
  router.get("/vapid-public-key", (_req, res) => {
    const publicKey = getVapidPublicKey();
    if (!publicKey) {
      res.status(404).json({ error: "VAPID not configured" });
      return;
    }
    res.json({ publicKey });
  });

  // POST /api/push/subscribe
  router.post("/subscribe", async (req, res) => {
    const { endpoint, keys, userId, companyId, deviceLabel } = req.body as {
      endpoint: string;
      keys: { p256dh: string; auth: string };
      userId?: string;
      companyId?: string;
      deviceLabel?: string;
    };

    if (!endpoint || !keys?.p256dh || !keys?.auth) {
      res.status(400).json({ error: "Missing required subscription fields" });
      return;
    }

    const id = await saveSubscription(db, {
      endpoint,
      p256dh: keys.p256dh,
      auth: keys.auth,
      userId,
      companyId,
      deviceLabel,
    });

    res.status(201).json({ id });
  });

  // DELETE /api/push/subscribe
  router.delete("/subscribe", async (req, res) => {
    const { endpoint } = req.body as { endpoint: string };

    if (!endpoint) {
      res.status(400).json({ error: "Missing endpoint" });
      return;
    }

    await removeSubscription(db, endpoint);
    res.status(204).end();
  });

  return router;
}
