import type { WeatherData } from '../types';

const DEFAULT_BASE_URL = 'https://api.openweathermap.org/data/2.5';

const trimTrailingSlash = (s: string) => s.replace(/\/+$/, '');

export const getWeatherData = async (lat: number, lon: number): Promise<WeatherData | null> => {
  const apiKey = import.meta.env.VITE_OWM_API_KEY;
  if (!apiKey) return null;

  const baseUrl = trimTrailingSlash(import.meta.env.VITE_OWM_BASE_URL ?? '') || DEFAULT_BASE_URL;
  const url = `${baseUrl}/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`;

  try {
    const response = await fetch(url);
    const data = await response.json();
    return {
      windSpeed: data.wind.speed,
      windAngle: data.wind.deg,
    };
  } catch {
    return null;
  }
};
