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

// Resolve package root via require.resolve, more reliable than __dirname in Docker/symlink scenarios
const packageRoot = path.dirname(require.resolve('@steedos-labs/plugin-workflow/package.json'));
const designerDistPath = path.join(packageRoot, 'designer', 'dist');
const amisRendererDistPath = path.join(designerDistPath, 'amis-renderer');

/**
 * 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
    res.sendFile(path.join(designerDistPath, 'index.html'), { dotfiles: 'allow' });
  } 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.)
 */
router.use('/api/workflow/designer-v2', express.static(designerDistPath));

/**
 * SPA fallback: serve index.html for any sub-path under /api/workflow/designer-v2/
 * that didn't match a static file (e.g. /form-designer, /form-designer?flowId=xxx).
 * Uses router.use to avoid path-to-regexp pattern syntax issues.
 */
router.use('/api/workflow/designer-v2', (req, res, next) => {
  // Only handle GET requests for HTML pages (skip API calls, static assets, etc.)
  if (req.method !== 'GET') return next();
  // Skip requests for static files (have a file extension)
  if (path.extname(req.path)) return next();
  // Must be a sub-path (not the root which is already handled)
  if (req.path === '/' || req.path === '') return next();

  requireAuthentication(req, res, () => {
    try {
      if (process.env.NODE_ENV === 'development') {
        return res.redirect('http://localhost:5173');
      }
      const designerIndex = path.join(designerDistPath, 'index.html');
      res.sendFile(designerIndex, { dotfiles: 'allow' });
    } catch (e) {
      res.status(500).send({
        errors: [{ errorMessage: e.message }]
      });
    }
  });
});

/**
 * Serve the amis renderer bundle (js + css).
 * URL: /api/workflow/amis-form-v2/amis-renderer.js
 *      /api/workflow/amis-form-v2/amis-renderer.css
 */
router.use('/api/workflow/amis-form-v2', express.static(amisRendererDistPath));

exports.default = router;
