import express from "express";
import jwt from "jsonwebtoken";
import WebsiteSubmission from "../models/websiteSubmission.js";
import SubmitDirectory from "../models/submitDirectory.js";
import SubmitAiWebsite from "../models/submitAiWebsite.js";
import {authenticate} from "../middleware/authMiddleware.js"
const router = express.Router();

// // ✅ Middleware to verify JWT and extract user
// function verifyToken(req, res, next) {
//   const authHeader = req.headers.authorization;
//   if (!authHeader || !authHeader.startsWith("Bearer ")) {
//     return res.status(401).json({ message: "No token provided" });
//   }

//   const token = authHeader.split(" ")[1];
//   try {
//     const decoded = jwt.verify(token, process.env.JWT_SECRET);
//     req.user = decoded; // decoded should contain user._id
//     next();
//   } catch (error) {
//     return res.status(403).json({ message: "Invalid token" });
//   }
// }


/**
 * Generic delete helper
 */
async function deleteByModel(Model, id, userId, res) {
  try {
    const record = await Model.findById(id);
    if (!record) {
      return res.status(404).json({ message: "Record not found" });
    }
     console.log("record.submittedBy:", record.submittedBy.toString());
     console.log("req.user.id:", userId);

    if (record.submittedBy.toString() !== userId.toString()) {
      return res.status(403).json({ message: "Not authorized to delete this entry" });
    }

    await record.deleteOne();
    res.status(200).json({ success: true, message: "Deleted successfully" });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: "Server error" });
  }
}

// 🎨 1️⃣ Delete WebsiteSubmission
router.delete("/website/:id", authenticate, async (req, res) => {
  await deleteByModel(WebsiteSubmission, req.params.id, req.user.id, res);
});

// 🏢 2️⃣ Delete SubmitDirectory
router.delete("/directory/:id", authenticate, async (req, res) => {
  await deleteByModel(SubmitDirectory, req.params.id, req.user.id, res);
});

// 🤖 3️⃣ Delete SubmitAiWebsite
router.delete("/ai/:id", authenticate, async (req, res) => {
  await deleteByModel(SubmitAiWebsite, req.params.id, req.user.id, res);
});

export default router;
