const express = require('express');
const router = express.Router();
const translate = require('google-translate-api-x');
const { ok, err } = require('../helpers/response');

router.post('/', async (req, res, next) => {
  try {
    const { text, from, to } = req.body;
    if (!text || !from || !to) return err(res, 'text, from, to wajib diisi');

    const result = await translate(text, { from, to });

    ok(res, {
      translated: result.text,
      from,
      to,
      detectedLang: result.from?.language?.iso || from,
    });
  } catch (e) {
    console.error('Translate error:', e.message);
    err(res, 'Gagal menerjemahkan: ' + e.message, 500);
  }
});

module.exports = router;
