exports.searchPlayers = async (req, res) => {
  const query = req.query.q;

  if (!query) {
    return res.status(400).json({ error: "Search query 'q' is required" });
  }

  try {
    // Search in the local database first
    const localPlayers = await Player.find({
      name: { $regex: query, $options: "i" },
    }).limit(5);

    if (localPlayers.length > 0) {
      return res.json({ count: localPlayers.length, players: localPlayers });
    }

    // If not found locally, fetch from API
    const playersResponse = await makeApiRequest("searchplayers.php", {
      p: query,
    });

    // Validate response structure
    if (
      !playersResponse ||
      playersResponse.response === null ||
      !Array.isArray(playersResponse.player)
    ) {
      return res
        .status(404)
        .json({ error: "No players found matching the query" });
    }

    // Limit to 5 players
    const limitedPlayers = playersResponse.player.slice(0, 5);

    // Enrich player data with necessary fields
    const enrichedPlayers = limitedPlayers.map((player) => ({
      player_id: player.idPlayer,
      name: player.strPlayer,
      position: player.strPosition || "N/A",
      nationality: player.strNationality || "N/A",
      team: player.strTeam || "N/A",
      league: player.strLeague || "N/A",
      photo_url: player.strThumb || null,
      description: player.strDescriptionEN || "No description available.",
      birthday: player.dateBorn || "N/A",
      height: player.strHeight || "N/A",
      weight: player.strWeight || "N/A",
      jerseyNumber: player.strNumber || "N/A",
      social: {
        twitter: player.strTwitter || null,
        facebook: player.strFacebook || null,
        instagram: player.strInstagram || null,
      },
    }));

    // Save fetched players to the local database
    await Player.insertMany(
      enrichedPlayers,
      { ordered: false } // Continue on duplicate errors
    ).catch((err) => {
      if (err.code === 11000) {
        console.warn("Duplicate player entries detected.");
      } else {
        console.error("Error inserting players into DB:", err.message);
      }
    });

    res.json({ count: enrichedPlayers.length, players: enrichedPlayers });
  } catch (error) {
    console.error("Error in searchPlayers:", error.message);
    res.status(500).json({ error: error.message });
  }
};

/**
 * Get detailed information about a specific player by ID using the new V1 API.
 */
exports.getPlayerDetails = async (req, res) => {
  const playerId = req.params.id;

  if (!playerId) {
    return res.status(400).json({ error: "Player ID is required" });
  }

  try {
    // Check local DB first
    const localPlayer = await Player.findOne({ player_id: playerId });

    if (localPlayer) {
      return res.json({ status: "success", response: localPlayer });
    }

    // If not found locally, fetch from API
    const playerDetailsResponse = await makeApiRequest("lookupplayer.php", {
      id: playerId,
    });

    // Validate response structure
    if (
      !playerDetailsResponse ||
      playerDetailsResponse.response === null ||
      !Array.isArray(playerDetailsResponse.player)
    ) {
      return res.status(404).json({ error: "Player not found" });
    }

    const player = playerDetailsResponse.player[0];

    // Structure the player details
    const detailedPlayer = {
      player_id: player.idPlayer,
      name: player.strPlayer,
      position: player.strPosition || "N/A",
      nationality: player.strNationality || "N/A",
      team: player.strTeam || "N/A",
      league: player.strLeague || "N/A",
      photo_url: player.strThumb || null,
      description: player.strDescriptionEN || "No description available.",
      birthday: player.dateBorn || "N/A",
      height: player.strHeight || "N/A",
      weight: player.strWeight || "N/A",
      jerseyNumber: player.strNumber || "N/A",
      social: {
        twitter: player.strTwitter || null,
        facebook: player.strFacebook || null,
        instagram: player.strInstagram || null,
      },
    };

    // Save to local DB
    try {
      await Player.create(detailedPlayer);
    } catch (err) {
      if (err.code === 11000) {
        console.warn("Player already exists in the database.");
      } else {
        console.error("Error inserting player into DB:", err.message);
      }
    }

    res.json({ status: "success", response: detailedPlayer });
  } catch (error) {
    console.error("Error in getPlayerDetails:", error.message);
    if (
      error.message.includes("404") ||
      error.message.toLowerCase().includes("not found")
    ) {
      res.status(404).json({ error: "Player not found" });
    } else {
      res.status(500).json({ error: error.message });
    }
  }
};
What is this code snnipit doing?