import type { APIRoute } from "astro";

export const GET: APIRoute = async ({ request }) => {
  const url = new URL(request.url);
  const city = url.searchParams.get("city");
  const lat = url.searchParams.get("lat");
  const lon = url.searchParams.get("lon");
  const apiKey = url.searchParams.get("apiKey");
  const units = url.searchParams.get("units") || "metric";

  if (!apiKey) {
    return new Response(JSON.stringify({ error: "Missing apiKey parameter" }), {
      status: 400,
      headers: {
        "Content-Type": "application/json",
      },
    });
  }

  if (!city && (!lat || !lon)) {
    return new Response(
      JSON.stringify({ error: "Missing city or lat/lon parameters" }),
      {
        status: 400,
        headers: {
          "Content-Type": "application/json",
        },
      },
    );
  }

  try {
    let weatherUrl;
    if (lat && lon) {
      weatherUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${encodeURIComponent(lat)}&lon=${encodeURIComponent(lon)}&appid=${apiKey}&units=${units}`;
    } else {
      const req = await fetch(
        `http://api.openweathermap.org/geo/1.0/direct?q=${city}&limit=1&appid=${apiKey}`,
      );

      const json = await req.json();

      const lata = json[0]?.lat | 0;

      const longa = json[0]?.lon | 0;

      weatherUrl = `https://api.openweathermap.org/data/2.5/weather?lat=${encodeURIComponent(lata)}&lon=${encodeURIComponent(longa)}&appid=${apiKey}&units=${units}`;
    }

    const response = await fetch(weatherUrl);

    if (!response.ok) {
      console.log(response);

      return new Response(
        JSON.stringify({ error: "Failed to fetch weather data" }),
        {
          status: response.status,
          headers: {
            "Content-Type": "application/json",
          },
        },
      );
    }

    const data = await response.json();

    return new Response(JSON.stringify(data), {
      status: 200,
      headers: {
        "Content-Type": "application/json",
        "Cache-Control": "public, max-age=300",
      },
    });
  } catch (error) {
    console.error("Weather API error:", error);
    return new Response(JSON.stringify({ error: "Internal server error" }), {
      status: 500,
      headers: {
        "Content-Type": "application/json",
      },
    });
  }
};
