const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');


const app = express();


app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'http://localhost:5176'); // Allow your frontend
    res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); // Allow required HTTP methods
    res.header('Access-Control-Allow-Headers', 'Content-Type'); // Allow required headers
    next();
});


app.post('/translate', async (req, res) => {
  const { text, target_lang } = req.body;

  console.log('Received request:', { text, target_lang });

  if (!text || !target_lang) {
    console.error('Invalid request payload:', req.body);
    return res.status(400).send('Missing text or target_lang');
  }

  try {
    const apiKey = '5e8b82a7-3595-466d-bb60-b11d5c128697:fx'; // Ensure this is set
    const response = await axios.post('https://api.deepl.com/v2/translate', {
      auth_key: apiKey,
      text,
      target_lang,
    });

    console.log('Translation API response:', response.data);
    res.status(200).json(response.data);
  } catch (error) {
    console.error('Error during translation:', error.response?.data || error.message);
    res.status(500).send('Error during translation.');
  }
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
