import { allCities, allCountries, getHottestAndColdestCityInCountry } from '$lib/db/queries';
import type { CityBasic, CityTemperature, CountryBasic, HotColdCity } from '$lib/types';
import { type Actions } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
// import { getLocationTemperature } from '$lib/server/meteoService';
// import { fetchAllCitiesTemperatures } from '$lib/server/meteoDataHandler';

const errorObject = {
  ok: false,
  data: null,
  error: 'Failed to fetch temperature'
}

export const load: PageServerLoad = async ({ url }) => {
  try {
    const countries = allCountries.all() as CountryBasic[];
    const cities = allCities.all() as CityBasic[];
    const country_id = url.searchParams.get('country');
    // console.log('country_id >>> ', country_id);

    let temperatureData: HotColdCity[] | null = null;
    if (country_id) {
      temperatureData = getHottestAndColdestCityInCountry.all({
        $country_id: Number(country_id),
        $date: new Date().toISOString().split('T')[0]
      }) as HotColdCity[];
    }

    // console.log('Loading >>>>', temperatureData);

    return {
      countries,
      cities,
      temperatureData,
      country_id: country_id ? parseInt(country_id) : null
    };
  } catch (error) {
    console.log(error);
    return {
      countries: [],
      cities: [],
      temperatureData: null,
      country_id: null
    };
  }
};

export const actions: Actions = {
  fetchTemperature: async ({ request }) => {
    try {
      const formData = await request.formData();
      const country_id = formData.get('country_id') as string;

      // console.log('FORM ACTION >>>', country_id)
      const response = getHottestAndColdestCityInCountry.all({
        $country_id: Number(country_id),
        $date: new Date().toISOString().split('T')[0]
      }) as HotColdCity[];

      if (response.length == 2) {
        // console.log('RESPONSE >>>>', response);

        return {
          ok: true,
          data: response,
          error: null,
          country_id: country_id ?? null
        };
      } else {
        return errorObject;
      }

    } catch (error) {
      console.log(error);
      return errorObject;
    }

  }
}
