import { json } from '@sveltejs/kit'; import { z } from 'zod'; import type { RequestHandler } from './$types'; import { requireAdmin } from '$lib/server/middleware/authorize.js'; import { create } from '$lib/server/services/appService.js'; import { success, error } from '$lib/server/utils/response.js'; const approveSchema = z.object({ services: z .array( z.object({ name: z.string().min(1), url: z.string().url(), source: z.enum(['docker', 'traefik']), icon: z.string().optional(), description: z.string().optional() }) ) .min(1) .max(100) }); /** * POST /api/admin/discover/approve — Approve discovered services and create app entries. Admin only. * * Body: { services: DiscoveredService[] } */ export const POST: RequestHandler = async (event) => { const user = requireAdmin(event); let rawBody: unknown; try { rawBody = await event.request.json(); } catch { return json(error('Invalid JSON body'), { status: 400 }); } const parsed = approveSchema.safeParse(rawBody); if (!parsed.success) { return json( error(`Validation failed: ${parsed.error.issues.map((i) => i.message).join(', ')}`), { status: 400 } ); } const body = parsed.data; const created: string[] = []; const errors: string[] = []; for (const service of body.services) { try { const app = await create({ name: service.name, url: service.url, icon: service.icon, description: service.description ?? `Discovered via ${service.source}`, category: 'Discovered', healthcheckEnabled: true, createdById: user.id }); created.push(app.id); } catch (err) { const message = err instanceof Error ? err.message : 'Unknown error'; errors.push(`Failed to create "${service.name}": ${message}`); } } return json( success({ created: created.length, errors }) ); };