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

export async function POST({ request, locals }) {
	try {
		const { characterId, tryCount, triedCharacterIds } = await request.json();
		const normalizedTriedCharacterIds = Array.isArray(triedCharacterIds)
			? triedCharacterIds.filter((id): id is string => typeof id === 'string')
			: [];

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

		const todayDate = getDateKey(new Date());

		// If user is logged in, check if they already played today
		if (locals.user) {
			// Get the characterHistoryId for today
			const [todayHistoryEntry] = await db
				.select({ id: characterHistory.id })
				.from(characterHistory)
				.where(eq(characterHistory.date, todayDate));

			if (todayHistoryEntry) {
				// Check if user already has a record for today
				const [existingRecord] = await db
					.select()
					.from(userCharacterHistory)
					.where(and(
						eq(userCharacterHistory.userId, locals.user.id),
						eq(userCharacterHistory.characterHistoryId, todayHistoryEntry.id)
					));

				// If user already played today, don't record again
				if (existingRecord) {
					return json({ success: false, message: 'Already played today' });
				}

				// 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));

				// Insert into userCharacterHistory
				await db.insert(userCharacterHistory).values({
					userId: locals.user.id,
					characterHistoryId: todayHistoryEntry.id,
					tryCount: tryCount,
					triedCharacterIds: normalizedTriedCharacterIds
				});
			}
		} else {
			// If user is not logged in, always increment counter
			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 });
	}
}
