import mongoose from "mongoose";
import express from "express";
import Vote from "../models/vote.js";
import WebsiteSubmission from "../models/websiteSubmission.js"; // import your Website model
import { authenticate } from "../middleware/authMiddleware.js";

const router = express.Router();

// Route to submit a vote for a website (POST)

router.post("/submit-vote", authenticate, async (req, res) => {
  try {
    const userId = req.user.id;
    const {
      websiteId,
      design,
      usability,
      creativity,
      content,
      score,
      overAllLabel,
    } = req.body;

    console.log("=== VOTE SUBMISSION DEBUG ===");
    console.log("Received websiteId:", websiteId);
    console.log("Type of websiteId:", typeof websiteId);

    // Convert websiteId string to ObjectId
    let websiteObjectId;
    try {
      websiteObjectId = new mongoose.Types.ObjectId(websiteId);
      console.log("Converted to ObjectId:", websiteObjectId);
    } catch (convertError) {
      console.log("Invalid ObjectId format");
      return res.status(400).json({ message: "Invalid website ID format" });
    }

    // Check if website exists using ObjectId
    const website = await WebsiteSubmission.findById(websiteObjectId);
    if (!website) {
      console.log("Website not found with ID:", websiteObjectId);
      // Let's check what websites actually exist
      const allWebsites = await WebsiteSubmission.find({}, '_id Title');
      console.log("Available websites:", allWebsites);
      return res.status(404).json({ message: "Website not found" });
    }

    console.log("Found website:", website._id);
    console.log("Website Title:", website.Title);
    console.log("Website current votes count:", website.Votes.length);

    // Check if this user already voted for this website
    const existingVote = await Vote.findOne({ 
      submittedBy: userId, 
      websiteId: websiteObjectId 
    });
    
    if (existingVote) {
      console.log("User already voted for this website");
      return res.status(400).json({ message: "You have already voted for this website" });
    }

    // Create new vote
    const newVote = new Vote({
      submittedBy: userId,
      websiteId: websiteObjectId, // Use the ObjectId
      design,
      usability,
      creativity,
      content,
      score,
      overAllLabel,
    });

    const savedVote = await newVote.save();
    console.log("Vote saved successfully with ID:", savedVote._id);

    // Push the vote _id into WebsiteSubmission's Votes array
    const updatedWebsite = await WebsiteSubmission.findByIdAndUpdate(
      websiteObjectId, // Use the ObjectId here too
      { 
        $push: { 
          Votes: savedVote._id 
        } 
      },
      { 
        new: true,
        runValidators: true 
      }
    );

    console.log("Website after update - Votes count:", updatedWebsite.Votes.length);
    console.log("Website Votes array:", updatedWebsite.Votes);

    res.status(201).json({ 
      message: "Vote submitted successfully", 
      data: savedVote,
      votesCount: updatedWebsite.Votes.length
    });

  } catch (err) {
    console.error("Error submitting vote:", err);
    console.error("Error details:", err.message);
    
    if (err.name === 'ValidationError') {
      return res.status(400).json({ 
        message: "Validation error", 
        error: err.message 
      });
    }
    
    res.status(500).json({ 
      message: "Error submitting vote", 
      error: err.message 
    });
  }
});

// Route to get all votes for a specific website by ID (GET by ID)
// router.get('/:websiteId', async (req, res) => {
//   try {
//     const { websiteId } = req.params;

//     // Fetch all votes for a specific websiteId, populate website data
//     const votes = await Vote.find({ websiteId })
//       .populate('websiteId', 'Title Country');  // Populate website details

//     if (!votes || votes.length === 0) {
//       return res.status(404).json({ message: 'No votes found for this website' });
//     }

//     res.status(200).json({ data: votes });
//   } catch (err) {
//     res.status(500).json({ message: 'Error fetching votes', error: err.message });
//   }
// });

export default router;
