import express from 'express';
import axios from 'axios';
import { requireAuth } from '../middleware/auth.js';

const router = express.Router();

router.get('/vehicles/search', requireAuth, async (req, res, next) => {
  try {
    const { query } = req.query;
    const token = process.env.CAR_API_TOKEN;

    if (!token) {
      return res.status(500).json({ error: 'CarAPI token not configured' });
    }

    // CarAPI search for trims
    const response = await axios.get('https://carapi.app/api/trims/v2', {
      params: {
        verbose: 'yes',
        year: 2020, // Default to a recent year or handle in query
        ...req.query
      },
      headers: {
        'accept': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    });

    res.json(response.data);
  } catch (err) {
    console.error('CarAPI Error:', err.response?.data || err.message);
    res.status(err.response?.status || 500).json({ 
      error: 'External API error',
      details: err.response?.data 
    });
  }
});

export default router;
