// pages/api/updateLocation.js
import mysql from "mysql";
import util from "util";

const dbConfig = {
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  port: process.env.DB_PORT,
  charset: "utf8mb4",
};

export default async function handler(req, res) {
  if (req.method !== "POST") {
    res.setHeader("Allow", ["POST"]);
    return res.status(405).end(`Method ${req.method} Not Allowed`);
  }

  const { id, latitude, longitude } = req.body;

  const connection = mysql.createConnection(dbConfig);
  // Promisify the query method
  const query = util.promisify(connection.query).bind(connection);

  try {
    await query("UPDATE poi SET position = POINT(?, ?) WHERE idPoi = ?", [
      longitude,
      latitude,
      id,
    ]);
    res.status(200).json({ success: true });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Ein Fehler ist aufgetreten" });
  } finally {
    connection.end();
  }
}
