const https = require("https");

async function testDeleteEndpoint() {
  console.log("=".repeat(50));
  console.log("Testing DELETE Endpoint - 403 Issue Diagnosis");
  console.log("=".repeat(50));
  console.log("");

  // Step 1: Login
  console.log("Step 1: Logging in to get token...");
  const token = await login();

  if (!token) {
    console.log("❌ Failed to get authentication token");
    process.exit(1);
  }

  console.log(`✅ Got token: ${token.substring(0, 30)}...`);
  console.log("");

  // Step 2: Test DELETE
  console.log("Step 2: Testing DELETE /api/lists/:id/songs/:songId");
  const listId = "24474ea3-6f34-4704-ac48-a80e1225d79e";
  const songId = "9831e027-aeb1-48a0-8763-fd3120f29692";

  await testDelete(listId, songId, token);
}

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

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

    const req = https.request(options, (res) => {
      let data = "";
      res.on("data", (chunk) => (data += chunk));
      res.on("end", () => {
        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(listId, songId, token) {
  return new Promise((resolve) => {
    const options = {
      hostname: "houseofprayer.ddns.net",
      port: 443,
      path: `/api/lists/${listId}/songs/${songId}`,
      method: "DELETE",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
      },
    };

    console.log(`URL: https://${options.hostname}${options.path}`);
    console.log("");

    const req = https.request(options, (res) => {
      let data = "";
      res.on("data", (chunk) => (data += chunk));
      res.on("end", () => {
        console.log(`HTTP Status: ${res.statusCode}`);
        console.log(`Response: ${data}`);
        console.log("");

        if (res.statusCode === 200 || res.statusCode === 204) {
          console.log("✅ SUCCESS! DELETE endpoint is working!");
          console.log("The 403 error has been fixed!");
        } else if (res.statusCode === 403) {
          console.log("❌ STILL GETTING 403 FORBIDDEN");
          console.log("");
          console.log("CRITICAL: The backend needs to be restarted!");
          console.log("");
          console.log("Run this command:");
          console.log("  sudo systemctl restart church-music-backend.service");
          console.log("");
          console.log("The code changes are in place, but the server");
          console.log("is running old code that doesn't have authentication.");
        } else if (res.statusCode === 401) {
          console.log("⚠️  Got 401 Unauthorized");
          console.log("Token is being checked but failing validation");
        } else if (res.statusCode === 404) {
          console.log("⚠️  Got 404 Not Found");
          console.log(
            "The list or song doesn't exist (this is expected if already deleted)",
          );
        } else {
          console.log(`⚠️  Unexpected status code: ${res.statusCode}`);
        }

        resolve();
      });
    });

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

    req.end();
  });
}

testDeleteEndpoint().catch(console.error);
