import { Router, Request, Response } from "express";
import { renderPdf, renderUrlPdf } from "../services/browser.js";
import { markdownToHtml, wrapHtml } from "../services/markdown.js";

export const convertRouter = Router();

interface ConvertBody {
  html?: string;
  markdown?: string;
  css?: string;
  format?: string;
  landscape?: boolean;
  margin?: { top?: string; right?: string; bottom?: string; left?: string };
  printBackground?: boolean;
  filename?: string;
}

// POST /v1/convert/html
convertRouter.post("/html", async (req: Request, res: Response) => {
  try {
    const body: ConvertBody =
      typeof req.body === "string" ? { html: req.body } : req.body;

    if (!body.html) {
      res.status(400).json({ error: "Missing 'html' field" });
      return;
    }

    // Wrap bare HTML fragments
    const fullHtml = body.html.includes("<html")
      ? body.html
      : wrapHtml(body.html, body.css);

    const pdf = await renderPdf(fullHtml, {
      format: body.format,
      landscape: body.landscape,
      margin: body.margin,
      printBackground: body.printBackground,
    });

    const filename = body.filename || "document.pdf";
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", `inline; filename="${filename}"`);
    res.send(pdf);
  } catch (err: any) {
    console.error("Convert HTML error:", err);
    res.status(500).json({ error: "PDF generation failed", detail: err.message });
  }
});

// POST /v1/convert/markdown
convertRouter.post("/markdown", async (req: Request, res: Response) => {
  try {
    const body: ConvertBody =
      typeof req.body === "string" ? { markdown: req.body } : req.body;

    if (!body.markdown) {
      res.status(400).json({ error: "Missing 'markdown' field" });
      return;
    }

    const html = markdownToHtml(body.markdown, body.css);
    const pdf = await renderPdf(html, {
      format: body.format,
      landscape: body.landscape,
      margin: body.margin,
      printBackground: body.printBackground,
    });

    const filename = body.filename || "document.pdf";
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", `inline; filename="${filename}"`);
    res.send(pdf);
  } catch (err: any) {
    console.error("Convert MD error:", err);
    res.status(500).json({ error: "PDF generation failed", detail: err.message });
  }
});

// POST /v1/convert/url
convertRouter.post("/url", async (req: Request, res: Response) => {
  try {
    const body = req.body as { url?: string; format?: string; landscape?: boolean; margin?: any; printBackground?: boolean; waitUntil?: string; filename?: string };

    if (!body.url) {
      res.status(400).json({ error: "Missing 'url' field" });
      return;
    }

    // Basic URL validation
    try {
      const parsed = new URL(body.url);
      if (!["http:", "https:"].includes(parsed.protocol)) {
        res.status(400).json({ error: "Only http/https URLs are supported" });
        return;
      }
    } catch {
      res.status(400).json({ error: "Invalid URL" });
      return;
    }

    const pdf = await renderUrlPdf(body.url, {
      format: body.format,
      landscape: body.landscape,
      margin: body.margin,
      printBackground: body.printBackground,
      waitUntil: body.waitUntil,
    });

    const filename = body.filename || "page.pdf";
    res.setHeader("Content-Type", "application/pdf");
    res.setHeader("Content-Disposition", `inline; filename="${filename}"`);
    res.send(pdf);
  } catch (err: any) {
    console.error("Convert URL error:", err);
    res.status(500).json({ error: "PDF generation failed", detail: err.message });
  }
});
