import type { PageServerLoad } from './$types'; import { prisma } from '$lib/db'; import { sendMail } from '$lib/server/resend'; import { isStaff } from '$lib/server/roles'; import { error } from '@sveltejs/kit'; function generateLicenseKey(): string { const hex = crypto.randomUUID().replace(/-/g, '').slice(0, 16).toUpperCase(); return `${hex.slice(0, 4)}-${hex.slice(4, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}`; } export const load: PageServerLoad = async () => { const records = await prisma.licenseKey.findMany({ include: { user: true }, orderBy: { key: 'asc' } }); return { records: records as unknown as Record[] }; }; export const actions = { createKey: async ({ request, locals }) => { if (!isStaff(locals)) throw error(403, 'Not authorized'); const formData = await request.formData(); const email = formData.get('email')?.toString()?.trim().toLowerCase(); if (!email) { return { success: false, action: 'createKey', error: 'Email is required' }; } const user = await prisma.user.findUnique({ where: { email } }); const key = generateLicenseKey(); await prisma.licenseKey.create({ data: { key, active: true, userId: user?.id, email: user ? undefined : email } }); try { const profile = await prisma.profile.findFirst({ where: user ? { userId: user.id } : { email } }); await sendMail({ to: email, subject: 'Your Radiant Wave License Key', templateId: 'license-key-delivery', data: { firstName: profile?.firstName ?? user?.name ?? 'Valued Customer', license_key: key } }); } catch (e) { console.error('Failed to send license key email:', e); } return { success: true, action: 'createKey' }; }, replace: async ({ request, locals }) => { if (!isStaff(locals)) throw error(403, 'Not authorized'); const formData = await request.formData(); const keyId = formData.get('id')?.toString(); if (!keyId) return { success: false, action: 'replace', error: 'Missing key id' }; const existing = await prisma.licenseKey.findUnique({ where: { id: keyId } }); if (!existing) return { success: false, action: 'replace', error: 'License key not found' }; await prisma.licenseKey.delete({ where: { id: keyId } }); await prisma.licenseKey.create({ data: { key: generateLicenseKey(), active: true, userId: existing.userId, email: existing.email } }); return { success: true, action: 'replace' }; } };