'use strict';
const express = require('express');
const router = express.Router();
const { requireAuthentication } = require("@steedos/auth");
const path = require('path');

/**
 * New React-based workflow designer
 * URL: /api/workflow/designer-v2
 */
router.get('/api/workflow/designer-v2', requireAuthentication, async (req, res) => {
  try {
    // In development, proxy to Vite dev server
    if (process.env.NODE_ENV === 'development') {
      return res.redirect('http://localhost:5173');
    }
    
    // In production, serve built React app
    const designerPath = path.join(__dirname, '../../../designer/dist/index.html');
    res.sendFile(designerPath);
  } catch (e) {
    res.status(500).send({
      errors: [{ errorMessage: e.message }]
    });
  }
});

/**
 * New designer startup API
 * URL: /api/designer-v2/startup
 */
router.get('/api/designer-v2/startup', requireAuthentication, async (req, res) => {
  try {
    const { getObject } = require('@steedos/objectql');
    
    // Get workspace data
    const space = await getObject("spaces").findOne(req.user.spaceId);
    
    // Return initialization data
    res.json({
      user: {
        userId: req.user.userId,
        name: req.user.name,
        spaceId: req.user.spaceId
      },
      space: space,
      message: 'New designer startup API - ready for implementation'
    });
  } catch (e) {
    res.status(500).send({
      errors: [{ errorMessage: e.message }]
    });
  }
});

/**
 * Serve static assets for production (js, css, images, etc.)
 */
const designerDistPath = path.join(__dirname, '../../../designer/dist');
router.use('/api/workflow/designer-v2', express.static(designerDistPath));

exports.default = router;
