// routes/websiteRoutes.js
import express from 'express';
import WebsiteSubmission from '../models/websiteSubmission.js';
import SubmitDirectory from '../models/submitDirectory.js';
import SubmitAiWebsite from '../models/submitAiWebsite.js';


const router = express.Router();

// Category filtering route
router.get('/category', async (req, res) => {
  try {
    const { category } = req.query;

    // Check if category parameter is provided
    if (!category) {
      return res.status(400).json({
        success: false,
        message: 'Category parameter is required'
      });
    }

    // Find websites where Category field matches (case-insensitive)
    const websites = await WebsiteSubmission.find({
  Category: { 
    $regex: category, 
    $options: 'i' // case-insensitive search
  }
})
.populate('submittedBy', 'userName') // populate the website owner
.populate({
  path: 'Votes',
  select: 'design usability creativity content score submittedBy',
  populate: {
    path: 'submittedBy',
    select: 'userName'
  }
})
.sort({ createdAt: -1 });
    res.status(200).json({
      success: true,
      count: websites.length,
      data: websites
    });

  } catch (error) {
    console.error('Error fetching websites by category:', error);
    res.status(500).json({
      success: false,
      message: 'Server error while fetching websites',
      error: error.message
    });
  }
});

// Technology filtering route
router.get('/technology', async (req, res) => {
  try {
    const { technology } = req.query;

    // Check if technology parameter is provided
    if (!technology) {
      return res.status(400).json({
        success: false,
        message: 'Technology parameter is required'
      });
    }

    // Find websites where Technology field matches (case-insensitive)
    const websites = await WebsiteSubmission.find({
      Technology: { 
        $regex: technology, 
        $options: 'i' // 'i' for case-insensitive
      }
    })
    .populate('submittedBy', 'userName') // populate user details
    .populate({
  path: 'Votes',             // populate votes
  select: 'design usability creativity content score submittedBy',
  populate: {
    path: 'submittedBy',
    select: 'userName'
  }
}) 
    .sort({ createdAt: -1 }); // sort by newest first

    res.status(200).json({
      success: true,
      count: websites.length,
      data: websites
    });

  } catch (error) {
    console.error('Error fetching websites by technology:', error);
    res.status(500).json({
      success: false,
      message: 'Server error while fetching websites',
      error: error.message
    });
  }
});



// routes/searchRoutes.js



// Global search across all 3 schemas
router.get('/', async (req, res) => {
  try {
    const { q: searchTerm } = req.query;

    // Check if search term is provided
    if (!searchTerm || searchTerm.trim() === '') {
      return res.status(400).json({
        success: false,
        message: 'Search term is required'
      });
    }

    const trimmedSearchTerm = searchTerm.trim();

    // Search across all 3 schemas simultaneously
    const [websiteResults, directoryResults, aiWebsiteResults] = await Promise.all([
      // 1. Search WebsiteSubmission schema
      WebsiteSubmission.find({
        $or: [
          { Title: { $regex: trimmedSearchTerm, $options: 'i' } },
          { Description: { $regex: trimmedSearchTerm, $options: 'i' } },
          { Category: { $regex: trimmedSearchTerm, $options: 'i' } },
          { Tags: { $regex: trimmedSearchTerm, $options: 'i' } },
          { Freelancer_Name: { $regex: trimmedSearchTerm, $options: 'i' } },
          { ProfileType: { $regex: trimmedSearchTerm, $options: 'i' } }
        ]
      })
      .populate('submittedBy', 'userName') // who submitted the website
.populate({
  path: 'Votes',
  select: 'design usability creativity content score submittedBy', // include submittedBy field
  populate: {
    path: 'submittedBy',
    select: 'userName' // who submitted the vote
  }
})
      .limit(20) // Limit results per schema
      .lean(),

      // 2. Search SubmitDirectory schema
      SubmitDirectory.find({
        $or: [
          { title: { $regex: trimmedSearchTerm, $options: 'i' } },
          { description: { $regex: trimmedSearchTerm, $options: 'i' } },
          { profile: { $regex: trimmedSearchTerm, $options: 'i' } },
          { country: { $regex: trimmedSearchTerm, $options: 'i' } },
          { languages: { $regex: trimmedSearchTerm, $options: 'i' } }
        ]
      })
      .populate('submittedBy', 'userName')
      .limit(20)
      .lean(),

      // 3. Search SubmitAiWebsite schema
      SubmitAiWebsite.find({
        $or: [
          { title: { $regex: trimmedSearchTerm, $options: 'i' } },
          { description: { $regex: trimmedSearchTerm, $options: 'i' } },
          { category: { $regex: trimmedSearchTerm, $options: 'i' } },
          { pricingOption: { $regex: trimmedSearchTerm, $options: 'i' } }
        ]
      })
      .populate('submittedBy', 'userName')
      .limit(20)
      .lean()
    ]);

    // Add type identifiers to each result
    const websiteResultsWithType = websiteResults.map(item => ({
      ...item,
      type: 'website'
    }));

    const directoryResultsWithType = directoryResults.map(item => ({
      ...item,
      type: 'directory'
    }));

    const aiWebsiteResultsWithType = aiWebsiteResults.map(item => ({
      ...item,
      type: 'ai_website'
    }));

    // Combine all results
    const allResults = [
      ...websiteResultsWithType,
      ...directoryResultsWithType,
      ...aiWebsiteResultsWithType
    ];

    res.status(200).json({
      success: true,
      searchTerm: trimmedSearchTerm,
      totalResults: allResults.length,
      breakdown: {
        websites: websiteResults.length,
        directories: directoryResults.length,
        ai_websites: aiWebsiteResults.length
      },
      data: allResults
    });

  } catch (error) {
    console.error('Global search error:', error);
    res.status(500).json({
      success: false,
      message: 'Server error during search',
      error: error.message
    });
  }
});



export default router;