const express = require('express');
const router = express.Router();
const Service = require('../models/Service');
const Portfolio = require('../models/Portfolio');

// Get all services
router.get('/', async (req, res) => {
  try {
    const category = req.query.category;
    const featured = req.query.featured;

    let query = { isActive: true };
    
    if (category && category !== 'all') {
      query.category = category;
    }
    
    if (featured === 'true') {
      query.featured = true;
    }

    const services = await Service.find(query)
      .populate('portfolio', 'title images')
      .sort({ featured: -1, order: 1 });

    res.json({
      success: true,
      services
    });
  } catch (error) {
    console.error('Services API error:', error);
    res.status(500).json({
      success: false,
      message: 'Error fetching services'
    });
  }
});

// Get single service
router.get('/:id', async (req, res) => {
  try {
    const service = await Service.findById(req.params.id)
      .populate('portfolio', 'title shortDescription images category');
    
    if (!service || !service.isActive) {
      return res.status(404).json({
        success: false,
        message: 'Service not found'
      });
    }

    // Get related services
    const relatedServices = await Service.find({
      _id: { $ne: service._id },
      category: service.category,
      isActive: true
    })
    .select('name shortDescription icon pricing')
    .limit(3);

    res.json({
      success: true,
      service,
      relatedServices
    });
  } catch (error) {
    console.error('Service detail API error:', error);
    res.status(500).json({
      success: false,
      message: 'Error fetching service'
    });
  }
});

// Get service categories
router.get('/meta/categories', async (req, res) => {
  try {
    const categories = await Service.distinct('category', { isActive: true });
    
    // Get count for each category
    const categoriesWithCount = await Promise.all(
      categories.map(async (category) => {
        const count = await Service.countDocuments({ 
          category, 
          isActive: true 
        });
        return { category, count };
      })
    );

    res.json({
      success: true,
      categories: categoriesWithCount
    });
  } catch (error) {
    console.error('Service categories API error:', error);
    res.status(500).json({
      success: false,
      message: 'Error fetching categories'
    });
  }
});

// Search services
router.get('/search/:term', async (req, res) => {
  try {
    const searchTerm = req.params.term;
    const limit = parseInt(req.query.limit) || 10;

    const services = await Service.find({
      $and: [
        { isActive: true },
        {
          $or: [
            { name: { $regex: searchTerm, $options: 'i' } },
            { description: { $regex: searchTerm, $options: 'i' } },
            { tags: { $in: [new RegExp(searchTerm, 'i')] } }
          ]
        }
      ]
    })
    .select('name shortDescription icon pricing category')
    .sort({ featured: -1, order: 1 })
    .limit(limit);

    res.json({
      success: true,
      services,
      searchTerm,
      count: services.length
    });
  } catch (error) {
    console.error('Service search API error:', error);
    res.status(500).json({
      success: false,
      message: 'Error searching services'
    });
  }
});

module.exports = router;