import { requireAuth } from '~/server/utils/auth' import { saveCanvasToGitea, loadCanvasFromGitea } from '~/server/utils/giteaApi' import { prisma } from '~/server/utils/prisma' export default defineEventHandler(async (event) => { const user = requireAuth(event) const body = await readBody(event) const { canvasId, action, commitMessage } = body if (!canvasId || !action) { throw createError({ statusCode: 400, message: 'Canvas ID and action are required' }) } try { switch (action) { case 'init': case 'sync': { const canvas = await prisma.canvas.findUnique({ where: { id: canvasId } }) if (!canvas) { throw createError({ statusCode: 404, message: 'Canvas not found' }) } if (canvas.ownerId !== user.id && !canvas.isPublic) { throw createError({ statusCode: 403, message: 'Access denied' }) } const opts = { username: user.username, groupId: canvas.groupId, isPublic: canvas.isPublic } const ok = await saveCanvasToGitea(canvasId, canvas, opts, commitMessage) return { success: ok, message: ok ? `Canvas ${canvasId} saved to Gitea` : `Failed to save canvas ${canvasId} to Gitea` } } case 'load': { const existing = await prisma.canvas.findUnique({ where: { id: canvasId } }) const opts = existing ? { username: user.username, groupId: existing.groupId, isPublic: existing.isPublic } : { username: user.username } const gitCanvas = await loadCanvasFromGitea(canvasId, opts) if (!gitCanvas) { return { success: false, message: 'Canvas not found in Gitea', needsInit: true } } if (existing) { await prisma.canvas.update({ where: { id: canvasId }, data: { nodes: gitCanvas.nodes || [], edges: gitCanvas.edges || [] } }) } return { success: true, canvas: gitCanvas, message: `Canvas ${canvasId} loaded from Gitea` } } default: throw createError({ statusCode: 400, message: 'Invalid action' }) } } catch (error: any) { console.error('Gitea sync error:', error) throw createError({ statusCode: 500, message: error?.message || 'Gitea operation failed' }) } })