// routes/favorites.js
import express from "express";
import { authenticate } from "../middleware/authMiddleware.js";
import mongoose from "mongoose";
import Favorite from "../models/favorite.js";

const router = express.Router();

// POST - Add to favorites
router.post("/", authenticate, async (req, res) => {
  try {
    const { itemType, itemId } = req.body;
    const userId = req.user.id;

    // Validate input
    if (!itemType || !itemId) {
      return res.status(400).json({
        success: false,
        message: "itemType and itemId are required",
      });
    }

    // Validate itemType
    if (!["nominee", "directory", "ai"].includes(itemType)) {
      return res.status(400).json({
        success: false,
        message: "Invalid itemType. Must be: nominee, directory, or ai",
      });
    }

    // Validate itemId is a valid MongoDB ObjectId
    if (!mongoose.Types.ObjectId.isValid(itemId)) {
      return res.status(400).json({
        success: false,
        message: "Invalid itemId format",
      });
    }

    // Determine the field name based on itemType
    const field =
      itemType === "nominee"
        ? "nomineeWebsite"
        : itemType === "directory"
          ? "directory"
          : "aiWebsite";

    // Check if already favorited
    const existingFavorite = await Favorite.findOne({
      user: userId,
      [field]: itemId,
    });

    if (existingFavorite) {
      return res.status(409).json({
        success: false,
        message: "Item already in favorites",
        favorite: existingFavorite,
      });
    }

    // Create favorite data
    const favoriteData = {
      user: userId,
      itemType: itemType,
      [field]: itemId,
    };

    // Save to database
    const favorite = new Favorite(favoriteData);
    await favorite.save();

    console.log(`✅ User ${userId} added ${itemType} ${itemId} to favorites`);

    res.status(201).json({
      success: true,
      message: "Added to favorites",
      favorite,
    });
  } catch (error) {
    console.error("❌ Error adding to favorites:", error);

    // Handle duplicate key error (in case unique index catches it)
    if (error.code === 11000) {
      return res.status(409).json({
        success: false,
        message: "Item already in favorites",
      });
    }

    res.status(500).json({
      success: false,
      message: "Server error while adding to favorites",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
});

// GET - Get user's favorites WITH ALL DATA
router.get("/", authenticate, async (req, res) => {
  try {
    const userId = req.user.id;

    console.log(`📋 Fetching favorites for user: ${userId}`);

    // Populate the actual data for the referenced fields with nested populate for submittedBy
    const favorites = await Favorite.find({ user: userId })
      .populate({
        path: "nomineeWebsite",
        select:
          "createdAt URL ProfileType Submitted_URL Title Img Description Category Colors Tags Freelancer_Name Country",
        populate: [
          {
            path: "submittedBy",
            select: "userName", // who submitted the website
          },
          {
            path: "Votes",
            select: "design usability creativity content score submittedBy", // include submittedBy field
            populate: {
              path: "submittedBy",
              select: "userName", // who submitted the vote
            },
          },
        ],
      })

      .populate({
        path: "directory",
        select:
          "title websiteUrl screenshot contactEmail contactNumber country profile openTo foundingYear totalEmployees description budget languages companyLogo facebook instagram linkedin twitter youtube tiktok createdAt ",
        populate: {
          path: "submittedBy",
          select: "userName email",
        },
      })
      .populate({
        path: "aiWebsite",
        select:
          "createdAt title websiteUrl screenshot category type pricingOption description",
        populate: {
          path: "submittedBy",
          select: "userName email",
        },
      })
      .sort({ createdAt: -1 }) // Changed from addedAt to createdAt
      .lean(); // Convert to plain JavaScript objects for better performance

    // Filter out any favorites where the referenced item was deleted OR has null submittedBy
    const validFavorites = favorites.filter((fav) => {
      // Check if the main item exists
      if (fav.itemType === "nominee" && !fav.nomineeWebsite) return false;
      if (fav.itemType === "directory" && !fav.directory) return false;
      if (fav.itemType === "ai" && !fav.aiWebsite) return false;

      // ⚠️ Optional: Filter out items with null submittedBy (uncomment if you want to hide these)
      // if (fav.itemType === 'nominee' && fav.nomineeWebsite && !fav.nomineeWebsite.submittedBy) return false;
      // if (fav.itemType === 'directory' && fav.directory && !fav.directory.submittedBy) return false;
      // if (fav.itemType === 'ai' && fav.aiWebsite && !fav.aiWebsite.submittedBy) return false;

      return true;
    });

    console.log(
      `✅ Found ${validFavorites.length} valid favorites (${favorites.length} total)`
    );

    res.json({
      success: true,
      count: validFavorites.length,
      favorites: validFavorites,
    });
  } catch (error) {
    console.error("❌ Error fetching favorites:", error.message);
    console.error(error.stack);
    res.status(500).json({
      success: false,
      message: "Server error while fetching favorites",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
});

// GET - Check if an item is already in the favorites list
router.get("/:itemId", authenticate, async (req, res) => {
  try {
    const { itemId } = req.params;
    const userId = req.user.id;

    // Validate itemId
    if (!mongoose.Types.ObjectId.isValid(itemId)) {
      return res.status(400).json({
        success: false,
        message: "Invalid itemId format",
        found: false,
      });
    }

    console.log(`🔍 Checking if user ${userId} has favorited item ${itemId}`);

    // Check if the item exists in the user's favorites
    const favorite = await Favorite.findOne({
      user: userId,
      $or: [
        { nomineeWebsite: itemId },
        { directory: itemId },
        { aiWebsite: itemId },
      ],
    }).lean();

    const found = !!favorite;

    console.log(
      `${found ? "✅" : "❌"} Item ${itemId} ${found ? "is" : "is not"} favorited`
    );

    res.json({
      success: true,
      found: found,
      favoriteId: favorite?._id,
    });
  } catch (error) {
    console.error("❌ Error checking favorite status:", error.message);
    res.status(500).json({
      success: false,
      message: "Server error while checking favorite status",
      found: false,
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
});

// DELETE - Remove from favorites based on itemId and itemType
router.delete("/", authenticate, async (req, res) => {
  try {
    const { itemType, itemId } = req.body;
    const userId = req.user.id;

    // Validate input
    if (!itemType || !itemId) {
      return res.status(400).json({
        success: false,
        message: "itemType and itemId are required",
      });
    }

    // Validate itemType
    if (!["nominee", "directory", "ai"].includes(itemType)) {
      return res.status(400).json({
        success: false,
        message: "Invalid itemType. Must be: nominee, directory, or ai",
      });
    }

    // Validate itemId
    if (!mongoose.Types.ObjectId.isValid(itemId)) {
      return res.status(400).json({
        success: false,
        message: "Invalid itemId format",
      });
    }

    // Create the field name dynamically based on itemType
    const field =
      itemType === "nominee"
        ? "nomineeWebsite"
        : itemType === "directory"
          ? "directory"
          : "aiWebsite";

    console.log(
      `🗑️  Attempting to remove ${itemType} ${itemId} from user ${userId}'s favorites`
    );

    // Remove the favorite document by itemId and itemType
    const result = await Favorite.findOneAndDelete({
      user: userId,
      [field]: itemId,
    });

    if (!result) {
      console.log(`❌ Favorite not found for deletion`);
      return res.status(404).json({
        success: false,
        message: "Favorite not found or already removed",
      });
    }

    console.log(`✅ Successfully removed favorite ${result._id}`);

    res.json({
      success: true,
      message: "Removed from favorites",
      removedId: result._id,
    });
  } catch (error) {
    console.error("❌ Error removing from favorites:", error.message);
    res.status(500).json({
      success: false,
      message: "Server error while removing from favorites",
      error: process.env.NODE_ENV === "development" ? error.message : undefined,
    });
  }
});

export default router;
