const AWS = require("aws-sdk");
const mongoose = require("mongoose");
const Game = require("../../models/gameModel");

const s3 = new AWS.S3({
  accessKeyId: process.env.AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  region: process.env.AWS_REGION,
});

// MongoDB Connection
const mongoURI = process.env.MONGODB_URL;
const dbName = process.env.MONGO_DB_NAME;

mongoose.connect(mongoURI, {
    dbName: dbName,
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => 
  console.log("Connected to MongoDB"))
  .catch((err) => console.error("MongoDB connection error:", err));

const saveGameScore2 = async (req, res) => {
  const { childId, gameName, gameID, gameTime, score, gameStar, screenShot } = req.body;

  try {
    if (!gameName || !childId || !gameID) {
      return res.status(400).json({ error: "Missing required fields" });
    }

    const newGame = new Game({
      gameName,
      childId,
      gameID,
      gameTime,
      score,
      gameStar,
    });

    // Save to MongoDB
    const result = await newGame.save();
    // Upload screenshot to S3 if provided
    if (screenShot) {
      let base64Image = screenShot.split(";base64,").pop();
      const buffer = Buffer.from(base64Image, "base64");

      const uploadParams = {
        Bucket: process.env.S3_BUCKET_NAME,
        Key: `images/${result._id}.png`,
        Body: buffer,
        ContentType: "image/png",
      };

      const s3Response = await s3.upload(uploadParams).promise();
      newGame.screenshotUrl = s3Response.Location;
      await newGame.save();
    }

    res.status(200).json({
      message: "Game data saved successfully",
      data: newGame,
    });
  } catch (error) {
    console.error("Error:", error);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

module.exports = saveGameScore2;
