const express = require("express");
const router = express.Router();
const auth = require("../middleware/auth");
const Post = require("../models/Post");
const Comment = require("../models/Comment");
const User = require("../models/User");
const multer = require("multer");
const path = require("path");
const fs = require("fs");

// Set Storage Engine
const storage = multer.diskStorage({
	destination: "./uploads/",
	filename: function (req, file, cb) {
		cb(
			null,
			file.fieldname + "-" + Date.now() + path.extname(file.originalname),
		);
	},
});

// Init Upload
const upload = multer({
	storage: storage,
	limits: { fileSize: 10000000 }, // 10MB
}).single("image");

// Create Post
router.post("/", auth, (req, res) => {
	upload(req, res, async (err) => {
		if (err) {
			return res.status(400).json({ msg: err });
		} else {
			if (req.file == undefined) {
				return res.status(400).json({ msg: "No File Selected!" });
			} else {
				try {
					// Build full image URL for frontend
					const baseUrl = req.protocol + "://" + req.get("host");
					const imageUrl = `https://eliazar.heliohost.us/uploads/${req.file.filename}`;

					const user = await User.findById(req.user.id);
					// Send to all friends
					const newPost = new Post({
						sender: req.user.id,
						recipients: user.friends,
						imageUrl: imageUrl,
						message: req.body.message,
					});

					const post = await newPost.save();
					res.json(post);
				} catch (err) {
					console.error(err);
					res.status(500).send("Server Error");
				}
			}
		}
	});
});

// Get Feed (Last photo from friends)
// Logic: Find the latest post where the current user is a recipient or sender?
// Locket usually shows the *latest* photo you received.
router.get("/feed", auth, async (req, res) => {
	try {
		// Find posts where recipient includes current user
		// Sort by date desc
		const posts = await Post.find({ recipients: req.user.id })
			.sort({ createdAt: -1 })
			.limit(20)
			.populate("sender", ["username"]);
		res.json(posts);
	} catch (err) {
		console.error(err.message);
		res.status(500).send("Server Error");
	}
});

// Get Latest Photo (For Widget)
router.get("/latest", auth, async (req, res) => {
	try {
		const post = await Post.findOne({ recipients: req.user.id })
			.sort({ createdAt: -1 })
			.populate("sender", ["username"]);
		res.json(post);
	} catch (err) {
		console.error(err.message);
		res.status(500).send("Server Error");
	}
});

// Delete Post
router.delete("/:id", auth, async (req, res) => {
	try {
		const post = await Post.findById(req.params.id);
		if (!post) {
			return res.status(404).json({ msg: "Post not found" });
		}

		// Check if user owns the post
		if (post.sender.toString() !== req.user.id) {
			return res.status(401).json({ msg: "Not authorized" });
		}

		// Delete image file
		if (post.imageUrl && post.imageUrl.startsWith("/uploads/")) {
			const imagePath = path.join(__dirname, "..", post.imageUrl);
			if (fs.existsSync(imagePath)) {
				fs.unlinkSync(imagePath);
			}
		}

		await post.deleteOne();
		res.json({ msg: "Post removed" });
	} catch (err) {
		console.error(err.message);
		res.status(500).send("Server Error");
	}
});

// Update Post
router.put("/:id", auth, (req, res) => {
	upload(req, res, async (err) => {
		if (err) {
			return res.status(400).json({ msg: err });
		}

		try {
			const post = await Post.findById(req.params.id);
			if (!post) {
				return res.status(404).json({ msg: "Post not found" });
			}

			if (post.sender.toString() !== req.user.id) {
				return res.status(401).json({ msg: "Not authorized" });
			}

			// Update message if provided
			if (req.body.message !== undefined) {
				post.message = req.body.message;
			}

			// Update image if provided
			if (req.file) {
				// Delete old image
				if (post.imageUrl && post.imageUrl.startsWith("/uploads/")) {
					const oldImagePath = path.join(__dirname, "..", post.imageUrl);
					if (fs.existsSync(oldImagePath)) {
						fs.unlinkSync(oldImagePath);
					}
				}
				post.imageUrl = `/uploads/${req.file.filename}`;
			}

			await post.save();
			const updatedPost = await Post.findById(post.id).populate("sender", [
				"username",
			]);
			res.json(updatedPost);
		} catch (err) {
			console.error(err.message);
			res.status(500).send("Server Error");
		}
	});
});

// Get Comments for a Post
router.get("/:id/comments", auth, async (req, res) => {
	try {
		const comments = await Comment.find({ post: req.params.id })
			.sort({ createdAt: 1 })
			.populate("user", ["username"]);
		res.json(comments);
	} catch (err) {
		console.error(err.message);
		res.status(500).send("Server Error");
	}
});

// Add Comment to a Post
router.post("/:id/comments", auth, async (req, res) => {
	try {
		const post = await Post.findById(req.params.id);
		if (!post) {
			return res.status(404).json({ msg: "Post not found" });
		}

		const newComment = new Comment({
			post: req.params.id,
			user: req.user.id,
			text: req.body.text,
		});

		const comment = await newComment.save();
		const populatedComment = await Comment.findById(comment.id).populate(
			"user",
			["username"],
		);
		res.json(populatedComment);
	} catch (err) {
		console.error(err.message);
		res.status(500).send("Server Error");
	}
});

module.exports = router;
