import { Router } from "express";
import { env } from "../../config/env.js";
import { HttpError } from "../../lib/errors.js";
import { enqueueBroadcastPush, enqueueSignalPush } from "../queues/push.queue.js";

export const internalRouter = Router();

internalRouter.use((req, res, next) => {
  const secret = req.header("x-parser-secret");
  if (!env.PARSER_INTERNAL_SECRET || secret !== env.PARSER_INTERNAL_SECRET) {
    return res.status(403).json({ message: "Forbidden" });
  }
  next();
});

internalRouter.post("/parser/signals-changed", async (req, res, next) => {
  try {
    const signalIds = Array.isArray(req.body?.signalIds)
      ? req.body.signalIds.filter((value: unknown): value is string => typeof value === "string")
      : [];

    const jobs = await Promise.all(
      signalIds.map((signalId: string) =>
        enqueueSignalPush({
          type: "signal",
          signalId
        })
      )
    );

    res.json({
      processed: signalIds.length,
      queued: jobs.length,
      jobs: jobs.map((job) => ({ id: job.id, signalId: job.data.signalId }))
    });
  } catch (error) {
    next(error);
  }
});

internalRouter.post("/broadcast", async (req, res, next) => {
  try {
    const title = String(req.body?.title ?? "").trim();
    const body = String(req.body?.body ?? "").trim();
    const url = req.body?.url ? String(req.body.url) : "/";
    const tag = req.body?.tag ? String(req.body.tag) : undefined;
    const renotify = Boolean(req.body?.renotify);

    if (!title || !body) {
      throw new HttpError(400, "Нужны title и body");
    }

    const job = await enqueueBroadcastPush({ type: "broadcast", title, body, url, tag, renotify });
    res.status(202).json({ queued: true, jobId: job.id });
  } catch (error) {
    next(error);
  }
});
