import { db } from '$lib/server/db';
import { arc } 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 arcs = await db.select().from(arc).orderBy(arc.name);

	return {
		arcs
	};
};

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

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

		if (!id) {
			return fail(400, { error: 'Arc ID is required' });
		}

		try {
			const updates: Record<string, any> = {};
			formData.forEach((value, key) => {
				if (key !== 'id') {
					if (key === 'startChapter' || key === 'endChapter') {
						updates[key] = value ? parseInt(value as string) : null;
					} else {
						updates[key] = value || null;
					}
				}
			});

			await db.update(arc).set(updates).where(eq(arc.id, id));
			return { success: true };
		} catch (error) {
			console.error('Arc update error:', error);
			return fail(500, { error: 'Failed to update arc' });
		}
	},

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

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

		if (!id) {
			return fail(400, { error: 'Arc ID is required' });
		}

		try {
			await db.delete(arc).where(eq(arc.id, id));
			return { success: true };
		} catch (error) {
			console.error('Arc delete error:', error);
			return fail(500, { error: 'Failed to delete arc' });
		}
	}
};

