import { db } from '$lib/server/db';
import { config } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
import { fail } from '@sveltejs/kit';
import type { PageServerLoad, Actions } from './$types';

export const load: PageServerLoad = async () => {
	const configEntries = await db.select().from(config);

	return {
		config: configEntries
	};
};

export const actions: Actions = {
	update: async ({ request, locals }) => {
		if (!locals.user?.isAdmin) {
			return fail(401, { error: 'Unauthorized' });
		}

		const formData = await request.formData();
		const key = formData.get('key') as string;
		const value = formData.get('value') as string;

		if (!key) {
			return fail(400, { error: 'Config key is required' });
		}

		try {
			await db
				.insert(config)
				.values({ key, value })
				.onConflictDoUpdate({ target: config.key, set: { value } });

			return { success: true };
		} catch (error) {
			console.error('Config update error:', error);
			return fail(500, { error: 'Failed to update configuration' });
		}
	},

	delete: async ({ request, locals }) => {
		if (!locals.user?.isAdmin) {
			return fail(401, { error: 'Unauthorized' });
		}

		const formData = await request.formData();
		const key = formData.get('key') as string;

		if (!key) {
			return fail(400, { error: 'Config key is required' });
		}

		try {
			await db.delete(config).where(eq(config.key, key));
			return { success: true };
		} catch (error) {
			console.error('Config delete error:', error);
			return fail(500, { error: 'Failed to delete configuration' });
		}
	}
};