import { Router } from "express";
import dotenv from "dotenv";

const router = Router();
dotenv.config();

router.get("/fetchWeather", async (req, res) => {
  const city = req.query.city;
  const units = req.query.units;
  const apiKey = process.env.API_KEY;

  try {
    const locationResponse = await fetch(
      `https://api.openweathermap.org/geo/1.0/direct?q=${city}&appid=${apiKey}`
    );
    if (!locationResponse.ok) {
      return res.status(500).json({
        error: "Error fetching location data. (Error: x32)",
        success: "false",
        data: null,
      });
    }
    const location = await locationResponse.json();
    if (!location || !location[0]) {
      return res.status(404).json({
        error: "Location not found.",
        success: "false",
        data: null,
      });
    }

    const lat = location[0].lat;
    const lon = location[0].lon;

    const weatherResponse = await fetch(
      `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=${units}`
    );

    if (!weatherResponse.ok) {
      return res.status(500).json({
        error: "Unexpected error! (Error: x33)",
        success: "false",
        data: null,
      });
    }

    const weather = await weatherResponse.json();

    res.status(200).json({
      error: "false",
      success: "Weather data fetched successfully!",
      data: weather,
    });
  } catch (err) {
    res.status(500).json({
      error: "Server error",
      success: "false",
      data: null,
    });
  }
});

export default router;
