require("dotenv").config();
const http = require("http");
const { neon } = require("@neondatabase/serverless");

const sql = neon(process.env.DATABASE_URL);

const requestHandler = async (req, res) => {
  if (req.method === "GET" && req.url === "/api/users") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ message: "GET is working" }));
    return;
  }  
  if (req.method === "POST" && req.url === "/api/users") {
    let body = "";

    req.on("data", (chunk) => {
      body += chunk.toString();
    });

    req.on("end", async () => {
      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;
        }

        // Check if user already exists
        const existing = await sql`
          SELECT * FROM users WHERE clerk_id = ${clerkId}
        `;

        if (existing.length > 0) {
          res.writeHead(200, { "Content-Type": "application/json" });
          res.end(JSON.stringify(existing[0]));
          return;
        }

        // Insert new user
        const result = await sql`
          INSERT INTO users (name, email, clerk_id)
          VALUES (${name}, ${email}, ${clerkId})
          RETURNING *;
        `;

        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" }));
      }
    });

    return;
  }

  // Fallback for unrecognized routes
  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");
});

