import type { Express } from "express";
import { createServer, type Server } from "http";
import { mailer } from "./utils/mail";

export async function registerRoutes(
  httpServer: Server,
  app: Express
): Promise<Server> {

  app.post("/contact", async (req, res) => {
    const { name, email, phone , subject, message } = req.body;

    try {
      await mailer.sendMail({
        from: `"Website Contact" <noreply@cadivity.com>`,
        to: "enquiry@cadivity.com",
        replyTo: email,
        subject: "New enquiry from website",
        text: `
          Name: ${name}
          Email: ${email}
          Phone: ${phone}
          Subject: ${subject}
          Message:${message}
        `,
      });

      app.get("/ping", (req, res) => {
        res.json({ ok: true, message: "Backend is reachable" });
      });

      res.json({ success: true });
    } catch (err) {
      console.error("Mail error:", err);
      res.status(500).json({ success: false, error: "Email failed" });
    }
  });

  return httpServer;
}
