import { requireAuth } from '~/server/utils/auth' import { saveCanvasToGitea, loadCanvasFromGitea } from '~/server/utils/giteaApi' import { canvases } from '~/server/utils/db' 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 = canvases.get(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 ok = await saveCanvasToGitea(canvasId, canvas, commitMessage) return { success: ok, message: ok ? `Canvas ${canvasId} saved to Gitea` : `Failed to save canvas ${canvasId} to Gitea` } } case 'load': { const gitCanvas = await loadCanvasFromGitea(canvasId) if (!gitCanvas) { return { success: false, message: 'Canvas not found in Gitea', needsInit: true } } const existing = canvases.get(canvasId) if (existing) { canvases.set(canvasId, { ...existing, 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' }) } })