// Direct backend test - bypassing Nginx
const http = require("http");

const testDirectBackend = async () => {
  console.log("Testing backend directly on localhost:8080...\n");

  // Step 1: Login
  const token = await login();
  if (!token) {
    console.log("❌ Failed to login");
    return;
  }
  console.log("✅ Got token:", token.substring(0, 40) + "...\n");

  // Step 2: Test DELETE directly on backend
  await testDelete(token);
};

function login() {
  return new Promise((resolve) => {
    const postData = JSON.stringify({
      username: "hop",
      password: "hopWorship2024",
    });

    const options = {
      hostname: "localhost",
      port: 8080,
      path: "/api/auth/login",
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Content-Length": postData.length,
      },
    };

    const req = http.request(options, (res) => {
      let data = "";
      res.on("data", (chunk) => (data += chunk));
      res.on("end", () => {
        console.log("Login response status:", res.statusCode);
        try {
          const json = JSON.parse(data);
          resolve(json.token || null);
        } catch (e) {
          console.log("Login response:", data);
          resolve(null);
        }
      });
    });

    req.on("error", (e) => {
      console.error("Login error:", e.message);
      resolve(null);
    });

    req.write(postData);
    req.end();
  });
}

function testDelete(token) {
  return new Promise((resolve) => {
    const listId = "24474ea3-6f34-4704-ac48-a80e1225d79e";
    const songId = "9831e027-aeb1-48a0-8763-fd3120f29692";

    const options = {
      hostname: "localhost",
      port: 8080,
      path: `/api/lists/${listId}/songs/${songId}`,
      method: "DELETE",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
    };

    console.log("Testing DELETE:", options.path);

    const req = http.request(options, (res) => {
      let data = "";
      res.on("data", (chunk) => (data += chunk));
      res.on("end", () => {
        console.log("\n=== RESULT ===");
        console.log("Status:", res.statusCode);
        console.log("Response:", data);

        if (res.statusCode === 200) {
          console.log("\n✅ SUCCESS! Backend DELETE works!");
          console.log("If you still get 403 in browser, the issue is NGINX.");
        } else if (res.statusCode === 403) {
          console.log("\n❌ 403 from backend - check auth middleware");
        } else if (res.statusCode === 401) {
          console.log("\n⚠️ 401 - Token issue");
        }

        resolve();
      });
    });

    req.on("error", (e) => {
      console.error("Request error:", e.message);
      console.log("\n❌ Backend might not be running!");
      console.log("Run: sudo systemctl restart church-music-backend.service");
      resolve();
    });

    req.end();
  });
}

testDirectBackend();
