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

	return {
		devilFruits
	};
};

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: 'Devil Fruit ID is required' });
		}

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

			await db.update(devilFruit).set(updates).where(eq(devilFruit.id, id));
			return { success: true };
		} catch (error) {
			console.error('Devil Fruit update error:', error);
			return fail(500, { error: 'Failed to update devil fruit' });
		}
	},

	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: 'Devil Fruit ID is required' });
		}

		try {
			await db.delete(devilFruit).where(eq(devilFruit.id, id));
			return { success: true };
		} catch (error) {
			console.error('Devil Fruit delete error:', error);
			return fail(500, { error: 'Failed to delete devil fruit' });
		}
	}
};

