import express from 'express';
import { Service, User } from '../models/index.js';
import { Op } from 'sequelize';

const router = express.Router();

router.get('/', async (req, res) => {
  try {
    const { category, provider, search, minPrice, maxPrice, page = 1, limit = 12 } = req.query;
    const offset = (page - 1) * limit;
    const where = { is_active: true };
    if (category) where.category = category;
    if (provider) where.provider_id = provider;
    if (search) where[Op.or] = [{ title: { [Op.like]: `%${search}%` } }, { description: { [Op.like]: `%${search}%` } }];
    if (minPrice || maxPrice) where.price = { ...(minPrice && { [Op.gte]: parseFloat(minPrice) }), ...(maxPrice && { [Op.lte]: parseFloat(maxPrice) }) };

    const { count, rows: services } = await Service.findAndCountAll({
      where, include: [{ model: User, as: 'provider', attributes: ['id', 'name', 'avatar', 'rating', 'review_count'] }],
      offset: parseInt(offset), limit: parseInt(limit), order: [['created_at', 'DESC']]
    });
    res.json({ services, total: count, page: parseInt(page), pages: Math.ceil(count / limit) });
  } catch (e) {
    res.status(500).json({ error: 'Failed to fetch services' });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const service = await Service.findByPk(req.params.id, {
      include: [{ model: User, as: 'provider', attributes: ['id', 'name', 'avatar', 'phone', 'rating', 'review_count', 'address'] }]
    });
    if (!service) return res.status(404).json({ error: 'Service not found' });
    res.json({ service });
  } catch (e) {
    res.status(500).json({ error: 'Failed to fetch service' });
  }
});

export default router;