import { Router, Request, Response } from "express";
import { createFreeKey } from "../services/keys.js";

const router = Router();

// Self-service free API key signup
router.post("/free", (req: Request, res: Response) => {
  const { email } = req.body;

  if (!email || typeof email !== "string") {
    res.status(400).json({ error: "Email is required" });
    return;
  }

  // Basic email validation
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
    res.status(400).json({ error: "Invalid email address" });
    return;
  }

  const keyInfo = createFreeKey(email.trim().toLowerCase());

  res.json({
    message: "Welcome to DocFast! 🚀",
    apiKey: keyInfo.key,
    tier: "free",
    limit: "100 PDFs/month",
    docs: "https://docfast.dev/docs",
    note: "Save this API key — it won't be shown again.",
  });
});

export { router as signupRouter };
