import { allCities, allCitiesWithNoTemperatureToday, cityTemperatureToday, insertCityTemperatureData } from "$lib/db/queries";
import type { CityBasic, CityTemperature } from "$lib/types";
import { getLocationTemperature } from "./meteoService";

const COOLDOWN_TIME = 333;

export const fetchAllCitiesTemperatures = async (date: string) => {
    try {

        const cities = allCitiesWithNoTemperatureToday.all({ $date: date }) as CityBasic[];

        console.log('Today date: ', date);
        console.log('Total Cities to fetch: ', cities.length);

        for (const [index, city] of cities.entries()) {
            try {
                console.log(`Processing city ${index + 1}/${cities.length}`);
                const existingRecord = cityTemperatureToday.get({ $id: city.id, $date: date }) as CityTemperature | null;
                if (!existingRecord) {
                    
                    const { data } = await getLocationTemperature(
                        city.id,
                        city.latitude.toString(),
                        city.longitude.toString()
                    );
                    if (data) {
                        insertCityTemperatureData.run({
                            $id: data.id,
                            $min: data.min,
                            $max: data.max,
                            $date: data.date
                        });
                        console.log(`Temperature data stored for ${city.name}`);
                    }
                    // Add cooldown delay to avoid API throttling
                    await new Promise(resolve => setTimeout(resolve, COOLDOWN_TIME));
                } else {
                    console.log(`Temperature data already exists for ${city.name}`);
                }


            } catch (error) {
                console.error(`Failed to fetch temperature for city ${city.name}:`, error);
            }
        }
        console.log('Finished fetching temperatures for all cities: ', date);
        return {
            ok: true,
        }
    } catch (error) {
        console.error('Failed to fetch cities:', error);
        return {
            ok: false
        }
    }
}