import type { MeteoData, MeteoResponseType } from "$lib/types";

export const getLocationTemperature = async (id: number, latitude: string, longitude: string) => {
    const meteoEndpoint = "https://api.open-meteo.com/v1/forecast";
    //   https://api.open-meteo.com/v1/forecast?latitude=48.0356&longitude=27.8129&hourly=temperature_2m&daily=temperature_2m_max,temperature_2m_min&forecast_days=1&format=json&timeformat=unixtime

    const url = new URL(meteoEndpoint);
    url.searchParams.set('latitude', latitude);
    url.searchParams.set('longitude', longitude);
    url.searchParams.set('daily', 'temperature_2m_max,temperature_2m_min');
    url.searchParams.set('format', 'json');
    url.searchParams.set('forecast_days', '1');


    try {
        const response = await fetch(url);
        if (response.ok) {
            const data = await response.json() as MeteoResponseType;
            console.log('Fetched DATA from open meteo >>>>');
            return {
                data: {
                    id,
                    max: data.daily.temperature_2m_max[0],
                    min: data.daily.temperature_2m_min[0],
                    date: data.daily.time[0],
                } as MeteoData
            };
        } else {
            return { data: null };
        }

    } catch (error) {
        console.log(error);
        return {
            data: null
        }
    }
}