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

	return {
		users: users.map((u) => ({
			...u,
			createdAt: new Date(u.createdAt).toLocaleDateString(),
			updatedAt: new Date(u.updatedAt).toLocaleDateString()
		}))
	};
};

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

		try {
			const updates: Record<string, any> = {
				name: formData.get('name') as string,
				email: formData.get('email') as string,
				isAdmin: formData.has('isAdmin'),
				emailVerified: formData.has('emailVerified')
			};

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

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

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