require("dotenv").config();
const http = require("http");
const { neon } = require("@neondatabase/serverless");
console.log("Server Started")
console.log("DATABASE_URL:", process.env.DATABASE_URL);
const sql = neon(process.env.DATABASE_URL);
const requestHandler = async (req, res) => {
  if (req.method === "POST" && req.url === "/signup") {
    let body = "";
    req.on("data", (chunk) => {
      body += chunk.toString();
    });

    req.on("end", async () => {
      console.log("🔹 Received signup request:", body);
      try {
        const { name, email, clerkId } = JSON.parse(body);

        if (!name || !email || !clerkId) {
          res.writeHead(400, { "Content-Type": "application/json" });
          res.end(JSON.stringify({ error: "Missing required fields" }));
          return;
        }
        console.log("🔹 Inserting user into database:", { name, email, clerkId });
        const result = await sql`
          INSERT INTO users (name, email, clerk_id)
          VALUES (${name}, ${email}, ${clerkId})
          RETURNING *;
        `;
        console.log("✅ User inserted:", result[0]);
        res.writeHead(201, { "Content-Type": "application/json" });
        res.end(JSON.stringify(result[0]));
      } catch (err) {
        console.error("Database Error:", err);
        res.writeHead(500, { "Content-Type": "application/json" });
        res.end(JSON.stringify({ error: "Database error" }));
      }
    });
  } else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("Not Found");
  }
};

http.createServer(requestHandler).listen(3000,"0.0.0.0", () => {
  console.log("✅ Server running at http://0.0.0.0:3000");
});

