import type { RequestHandler } from './$types';
import { db } from '$lib/server/db';
import { dailyCompletions } from '$lib/server/db/schema';
import { json } from '@sveltejs/kit';
import crypto from 'node:crypto';

const DEV_HOSTS = ['localhost:5173', 'test.bibdle.com'];

// A spread of book IDs to use as fake guesses
const SAMPLE_BOOK_IDS = [
	'GEN', 'EXO', 'PSA', 'PRO', 'ISA', 'JER', 'MAT', 'MRK', 'LUK', 'JHN',
	'ROM', 'GAL', 'EPH', 'PHP', 'REV', 'ACT', 'HEB', 'JAS', '1CO', '2CO',
];

export const POST: RequestHandler = async ({ request }) => {
	const host = request.headers.get('host') ?? '';
	if (!DEV_HOSTS.includes(host)) {
		return json({ error: 'Not allowed in production' }, { status: 403 });
	}

	try {
		const { anonymousId, days = 10 } = await request.json();

		if (!anonymousId || typeof anonymousId !== 'string') {
			return json({ error: 'anonymousId required' }, { status: 400 });
		}

		const today = new Date();
		const inserted: string[] = [];
		const skipped: string[] = [];

		for (let i = 1; i <= days; i++) {
			const d = new Date(today);
			d.setDate(d.getDate() - i);
			const date = d.toLocaleDateString('en-CA'); // YYYY-MM-DD

			const guessCount = Math.floor(Math.random() * 6) + 1; // 1-6 guesses
			// Pick `guessCount` random books (last one is the "correct" answer)
			const shuffled = [...SAMPLE_BOOK_IDS].sort(() => Math.random() - 0.5);
			const guesses = shuffled.slice(0, guessCount);

			try {
				await db.insert(dailyCompletions).values({
					id: crypto.randomUUID(),
					anonymousId,
					date,
					guessCount,
					guesses: JSON.stringify(guesses),
					completedAt: new Date(d.getTime() + 12 * 60 * 60 * 1000), // noon on that day
				});
				inserted.push(date);
			} catch (err: any) {
				if (err?.code === 'SQLITE_CONSTRAINT_UNIQUE' || err?.message?.includes('UNIQUE')) {
					skipped.push(date);
				} else {
					throw err;
				}
			}
		}

		return json({ success: true, inserted, skipped });
	} catch (err) {
		console.error('Error seeding history:', err);
		return json({ error: 'Failed to seed history' }, { status: 500 });
	}
};
