import { json, error } from '@sveltejs/kit';
import { existsSync } from 'fs';
import { DatabaseSync } from 'node:sqlite';
import { loadHomeScreenUsers } from '../../../lib/server/emby-user-db.js';
import { applyCachedEmbyNames } from '../../../lib/server/emby-user-cache.js';

export async function POST({ request }) {
	const { dbPath } = await request.json();
	if (!dbPath) throw error(400, 'No dbPath provided');
	if (!existsSync(dbPath)) throw error(404, `Database file not found: ${dbPath}`);

	let db;
	try {
		db = new DatabaseSync(dbPath, { readOnly: true });
		const result = loadHomeScreenUsers(db);
		const enriched = applyCachedEmbyNames(result.users);
		db.close();
		return json({
			...result,
			users: enriched.users,
			validation: {
				...result.validation,
				embyCacheMatchedUsers: enriched.cache.matchedCount,
				embyCacheUserCount: enriched.cache.totalCachedUsers,
				embyCacheLastSyncedAt: enriched.cache.lastSyncedAt
			}
		});
	} catch (err) {
		if (db) try { db.close(); } catch { /* ignore */ }
		throw error(500, err.message);
	}
}
