import { error } from '@sveltejs/kit';
import { getAllDevilFruitsFromCharacters, getOrCreateTodayFruit, getYesterdayFruit, getTodayFruitWinsCount } from '$lib/server/daily-fruit';
import { getAllCharacters } from '$lib/server/daily-character';

export async function load(event) {
    const fruits = await getAllDevilFruitsFromCharacters();
    const dailyFruit = await getOrCreateTodayFruit();

    if (!dailyFruit) {
        throw error(404, 'No daily fruit available. Please check if devil fruits are configured from characters.');
    }

    const yesterdayFruit = await getYesterdayFruit(new Date());

    // Load all characters for searching and filter only those with a devil fruit
    const allCharacters = await getAllCharacters();
    const characters = allCharacters.filter((c) => c.devilFruitId);

    // Find the character tied to the chosen fruit among characters that have a devil fruit
    const dailyCharacter = characters.find((c) => c.devilFruitId === dailyFruit.id) ?? null;

    const winCount = await getTodayFruitWinsCount(dailyFruit.id);

    return {
        fruits,
        dailyFruit,
        dailyCharacter,
        yesterdayFruit,
        winCount,
        characters
    };
}
