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

const router = express.Router();

router.get('/', async (req, res) => {
  try {
    const { data } = await api.get('/public/blogs', { params: { page: req.query.page, limit: 9 } });
    res.render('pages/blog-list', { title: 'Blog', blogs: data.blogs, pagination: data.pagination });
  } catch (err) {
    console.error('Blog list error:', err.message);
    res.render('pages/blog-list', { title: 'Blog', blogs: [], pagination: { page: 1, limit: 9, total: 0, totalPages: 1 } });
  }
});

router.get('/:slug', async (req, res) => {
  try {
    const { data } = await api.get(`/public/blogs/${req.params.slug}`);
    res.render('pages/blog-details', { title: data.title, blog: data });
  } catch (err) {
    if (err.response?.status === 404) {
      return res.status(404).render('pages/404', { title: 'Post Not Found' });
    }
    console.error('Blog detail error:', err.message);
    res.status(500).render('pages/404', { title: 'Something Went Wrong' });
  }
});

export default router;
