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

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

	let db;
	try {
		db = new DatabaseSync(dbPath);
		const userLookup = loadUserLookup(db);

		const keyRow = db
			.prepare("SELECT UserSettingsKeyId FROM UserSettingsKeys WHERE Name = 'homescreensettings'")
			.get();
		if (!keyRow) throw new Error("'homescreensettings' key not found in UserSettingsKeys table");
		const keyId = keyRow.UserSettingsKeyId;

		const checkStmt = db.prepare(
			'SELECT 1 FROM UserSettings WHERE UserId = ? AND UserSettingsKeyId = ?'
		);
		const updateStmt = db.prepare(
			'UPDATE UserSettings SET Value = ? WHERE UserId = ? AND UserSettingsKeyId = ?'
		);
		const insertStmt = db.prepare(
			'INSERT INTO UserSettings (UserId, UserSettingsKeyId, Value) VALUES (?, ?, ?)'
		);

		let count = 0;
		let normalizedSections = 0;

		// node:sqlite transactions: use db.exec('BEGIN') / db.exec('COMMIT') manually
		// or wrap in a function with db.transaction() if supported
		db.exec('BEGIN');
		try {
			for (const { userId, sections } of changes) {
				const user = userLookup.get(String(userId));
				if (!user) {
					throw new Error(`UserId ${userId} does not exist in ${dbPath}`);
				}

				const nextSections = normalizeSectionsForUser(sections, user.embyGuid);
				if (JSON.stringify(nextSections) !== JSON.stringify(sections)) {
					normalizedSections += nextSections.length;
				}

				const value = JSON.stringify({ Sections: nextSections });
				const exists = checkStmt.get(userId, keyId);
				if (exists) {
					updateStmt.run(value, userId, keyId);
				} else {
					insertStmt.run(userId, keyId, value);
				}
				count++;
			}
			db.exec('COMMIT');
		} catch (err) {
			db.exec('ROLLBACK');
			throw err;
		}

		db.close();
		return json({ ok: true, count, normalizedSections });
	} catch (err) {
		if (db) try { db.close(); } catch { /* ignore */ }
		throw error(500, err.message);
	}
}
