import { json } from '@sveltejs/kit';
import { db } from '$lib/server/db';
import { devilFruitHistory } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
import { sql } from 'drizzle-orm';
import { getDateKey } from '$lib/server/daily-fruit';

export async function POST({ request, locals }) {
    try {
        const { characterId, tryCount, triedCharacterIds } = await request.json();

        if (!characterId) {
            return json({ error: 'Missing characterId' }, { status: 400 });
        }

        const todayDate = getDateKey(new Date());

        // Increment the won counter for today's devil fruit entry
        await db
            .update(devilFruitHistory)
            .set({
                won: sql`${devilFruitHistory.won} + 1`,
                updatedAt: Date.now()
            })
            .where(eq(devilFruitHistory.date, todayDate));

        return json({ success: true });
    } catch (error) {
        console.error('Error recording fruit win:', error);
        return json({ error: 'Failed to record win' }, { status: 500 });
    }
}
