import express from 'express';
import api from '../config/api.js';

const router = express.Router();

router.get('/', async (req, res) => {
  const { search, category, country, state, city, page } = req.query;
  try {
    const { data } = await api.get('/public/tours', { params: { search, category, country, state, city, page, limit: 12 } });
    res.render('pages/tour-listing', {
      title: 'Tour Packages',
      tours: data.tours,
      pagination: data.pagination,
      filters: req.query
    });
  } catch (err) {
    console.error('Tour listing error:', err.message);
    res.render('pages/tour-listing', {
      title: 'Tour Packages',
      tours: [],
      pagination: { page: 1, limit: 12, total: 0, totalPages: 1 },
      filters: req.query
    });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const { data } = await api.get(`/public/tours/${req.params.id}`);
    const relatedRes = await api.get('/public/tours', { params: { category: data.p_category, limit: 4 } });
    const related = relatedRes.data.tours.filter((t) => t.p_id !== data.p_id).slice(0, 3);
    res.render('pages/tour-details', { title: data.p_name, tour: data, related });
  } catch (err) {
    if (err.response?.status === 404) {
      return res.status(404).render('pages/404', { title: 'Tour Not Found' });
    }
    console.error('Tour detail error:', err.message);
    res.status(500).render('pages/404', { title: 'Something Went Wrong' });
  }
});

export default router;
