import express from 'express';
import { canvasDb } from '../database/db.js';

const router = express.Router();

// GET /api/canvas/:projectName — load canvas for a project
router.get('/:projectName', async (req, res) => {
  try {
    const userId = req.user.id;
    const { projectName } = req.params;

    const canvas = await canvasDb.load(userId, decodeURIComponent(projectName));
    if (!canvas) {
      return res.json({ elements: [], appState: {}, updatedAt: null });
    }
    res.json(canvas);
  } catch (err) {
    res.status(500).json({ error: 'Failed to load canvas' });
  }
});

// POST /api/canvas/:projectName — save canvas for a project
router.post('/:projectName', async (req, res) => {
  try {
    const userId = req.user.id;
    const { projectName } = req.params;
    const { elements, appState } = req.body;

    if (!Array.isArray(elements)) {
      return res.status(400).json({ error: 'elements must be an array' });
    }

    await canvasDb.save(userId, decodeURIComponent(projectName), elements, appState || {});
    res.json({ ok: true });
  } catch (err) {
    res.status(500).json({ error: 'Failed to save canvas' });
  }
});

// DELETE /api/canvas/:projectName — delete canvas for a project
router.delete('/:projectName', async (req, res) => {
  try {
    const userId = req.user.id;
    const { projectName } = req.params;

    const deleted = await canvasDb.delete(userId, decodeURIComponent(projectName));
    res.json({ ok: true, deleted });
  } catch (err) {
    res.status(500).json({ error: 'Failed to delete canvas' });
  }
});

export default router;
