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

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

export const load: PageServerLoad = () => {
  try {
    const countries = allCountries.all() as CountryBasic[];
    const cities = allCities.all() as CityBasic[];
    return {
      countries,
      cities
    };
  } catch (error) {
    console.log(error);
    return {
      countries: [],
      cities: []
    };
  }
};

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

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

      // if (response.length == 2) {
      //   console.log(response.data);

      //   return {
      //     ok: true,
      //     data: response.data,
      //     error: null
      //   };
      // } else {
        return errorObject;
      // }
      // return {
      // 	ok: true,
      // 	data: response,
      // 	error: null
      // }
    } catch (error) {
      console.log(error);
      return errorObject;
    }

  }
}
