import { Router } from "express";
import multer from "multer";
import cloudinary from "../config/cloudinary.js";
import ImageDetection from "../models/image-detections.js";
import User from "../models/user.js";
import passport from "passport";
import ProfilePicture from "../models/profile-picture.js";

const router = Router();
const upload = multer({ storage: multer.memoryStorage() });

router.post(
  "/upload-detection-image",
  passport.authenticate("jwt", { session: false }),
  upload.single("image"),
  async (req, res) => {
    try {
      if (!req.file) return res.status(400).json({ error: "No file uploaded" });
      const predictionData = {
        predicted_class: req.body.predicted_class,
        probabilities: {
          Karsinoma: parseFloat(req.body.probabilities.Karsinoma),
          Kulit_Sehat: parseFloat(req.body.probabilities.Kulit_Sehat),
          Melanoma: parseFloat(req.body.probabilities.Melanoma),
        },
      };
      console.log(req.body);

      // Validate prediction data
      if (
        !predictionData.predicted_class ||
        !predictionData.probabilities ||
        Object.values(predictionData.probabilities).some(isNaN)
      ) {
        return res.status(400).json({ error: "Invalid prediction data" });
      }

      const detectionPercentage =
        parseFloat(req.body.detectionPercentage) || 0.0;

      const upload_stream = cloudinary.uploader.upload_stream(
        {
          folder: "imageDetection",
          format: "webp",
          // quality: "auto:good",
          // transformation: { width: 800, height: 600, crop: "limit" },
        },
        async (error, result) => {
          if (error) throw error;
          const image = new ImageDetection({
            cloudinaryUrl: result.secure_url,
            public_id: result.public_id,
            uploadedBy: req.user._id,
            verification: null,
            prediction: predictionData,
          });

          await image.save();

          res
            .status(201)
            .json({ message: "Image uploaded successfully", image });
        },
      );
      upload_stream.end(req.file.buffer);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  },
);

router.post(
  "/upload-profile-picture",
  passport.authenticate("jwt", { session: false }),
  upload.single("image"),
  async (req, res) => {
    try {
      if (!req.file) return res.status(400).json({ error: "No file uploaded" });

      const userId = req.user._id;
      // 1. Find user's current profile picture public_id
      const user = await User.findById(userId);
      if (!user) return res.status(404).json({ error: "User not found" });
      let oldProfilePicture = null;
      if (user.profilePictureUrl) {
        oldProfilePicture = await ProfilePicture.findOne({
          cloudinaryUrl: user.profilePictureUrl,
        });
      }

      const upload_stream = cloudinary.uploader.upload_stream(
        {
          folder: "profilePictures",
          format: "webp",
          // quality: "auto:good",
          // transformation: { width: 800, height: 600, crop: "limit" },
        },
        async (error, result) => {
          if (error) throw error;
          const profilePicture = new ProfilePicture({
            cloudinaryUrl: result.secure_url,
            public_id: result.public_id,
            uploadedBy: req.user._id,
          });

          await profilePicture.save();

          user.profilePictureUrl = result.secure_url;
          await user.save();

          if (oldProfilePicture) {
            await cloudinary.uploader.destroy(oldProfilePicture.public_id);
            await oldProfilePicture.deleteOne();
          }

          res.status(201).json({
            message: "Profile picture uploaded successfully",
            profilePicture,
          });
        },
      );
      upload_stream.end(req.file.buffer);
    } catch (error) {
      res.status(500).json({ error: error.message });
    }
  },
);

router.patch(
  "/users/:id/profile-picture",
  passport.authenticate("jwt", { session: false }),
  async (req, res) => {
    try {
      const { id } = req.params;
      const { profilePictureUrl } = req.body;

      const user = await User.findByIdAndUpdate(
        id,
        { profilePictureUrl },
        { new: true },
      );

      if (!user) return res.status(404).json({ message: "User not found" });

      res.status(200).json({
        message: "Profile picture updated successfully",
        user,
      });
    } catch (err) {
      console.error(err);
      res.status(500).json({ message: "Failed to update profile picture" });
    }
  },
);

export default router;
