// server/routes/ai/planExport.ts
import { Router } from "express";
import { renderPlanPDF, renderPlanDOCX, PlanResponse } from "../../services/exportTemplates";

const router = Router();

/** Simple auth stub — replace with your real auth middleware */
function requireAuth(req: any, res: any, next: any) {
  if (!req.user) return res.status(401).json({ error: "Unauthorized" });
  next();
}

router.post("/api/ai/plan/export", requireAuth, async (req: any, res) => {
  try {
    const { plan, format, businessName } = req.body as { plan: PlanResponse; format: "pdf"|"docx"; businessName?: string };
    if (!plan || !format) return res.status(400).json({ error: "Missing plan or format" });
    if (!req.user?.isPaid) return res.status(402).json({ error: "Payment required", code: "PAYWALL" });

    const meta = {
      businessName: businessName || inferBusinessName(plan) || "Your Business",
      subtitle: "Business Plan",
      generatedAt: new Date(),
    };

    if (format === "pdf") {
      const doc = renderPlanPDF(plan, meta);
      const filename = slugify(`${meta.businessName}-Business-Plan.pdf`);
      res.setHeader("Content-Type", "application/pdf");
      res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
      doc.pipe(res);
      doc.end();
      return;
    }

    if (format === "docx") {
      const buffer = await renderPlanDOCX(plan, meta);
      const filename = slugify(`${meta.businessName}-Business-Plan.docx`);
      res.setHeader("Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
      res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
      return res.send(buffer);
    }

    return res.status(400).json({ error: "Invalid format" });
  } catch (err: any) {
    console.error("plan/export error:", err);
    return res.status(500).json({ error: "Failed to export plan" });
  }
});

function inferBusinessName(plan: PlanResponse): string | undefined {
  // Try to find a name in the Executive Summary or Summary section; this is optional.
  const guess = plan.sections.find(s => /executive summary|summary/i.test(s.title));
  if (!guess) return undefined;
  const m = guess.content.match(/^\s*([A-Z][A-Za-z0-9&\-\s]{2,40})\s+(?:is|builds|creates|designs)\b/);
  return m?.[1]?.trim();
}

function slugify(s: string) {
  return s.replace(/[^\w\s\-\.]/g, "").replace(/\s+/g, "-");
}

export default router;
