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

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

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

		const todayDate = getDateKey(new Date());

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

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