const express = require('express');
const router = express.Router();

// Proxy ke Aladhan API — bypass CSP connect-src restriction
router.get('/by-city', async (req, res) => {
  const { city, country, method } = req.query;
  try {
    const url = `https://api.aladhan.com/v1/timingsByCity?city=${encodeURIComponent(city || 'Surabaya')}&country=${encodeURIComponent(country || 'Indonesia')}&method=${method || 11}`;
    const response = await fetch(url);
    const data = await response.json();
    res.json(data);
  } catch (err) {
    res.status(500).json({ code: 500, status: 'ERROR', data: null });
  }
});

router.get('/by-coords', async (req, res) => {
  const { latitude, longitude, method } = req.query;
  try {
    const url = `https://api.aladhan.com/v1/timings?latitude=${latitude}&longitude=${longitude}&method=${method || 11}`;
    const response = await fetch(url);
    const data = await response.json();
    res.json(data);
  } catch (err) {
    res.status(500).json({ code: 500, status: 'ERROR', data: null });
  }
});

router.get('/reverse-geocode', async (req, res) => {
  const { lat, lon } = req.query;
  try {
    const url = `https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json&accept-language=id`;
    const response = await fetch(url, {
      headers: { 'User-Agent': 'Nuralilm/1.0' }
    });
    const data = await response.json();
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: 'Geocode failed' });
  }
});

module.exports = router;
