import express from 'express';
import { authenticateToken } from '../middleware/auth.js';
import ConfigService from '../services/ConfigService.js';
import Project from '../models/Project.js';

const router = express.Router();

/**
 * PHASE 1: Configuration Endpoint
 * Returns application-wide configuration and feature flags
 * No authentication required - public configuration only
 */

// Get application configuration
router.get('/', async (req, res, next) => {
  try {
    const config = {
      status: 'success',
      code: 'CONFIG_RETRIEVED',
      message: 'Configuration retrieved successfully',
      data: {
        app: {
          name: 'Design System Swarm',
          version: '1.0.0',
          environment: process.env.NODE_ENV || 'development'
        },
        features: {
          authentication: {
            enabled: true,
            jwtExpiry: 3600
          },
          notifications: {
            enabled: process.env.NOTIFICATIONS_ENABLED === 'true',
            sse: {
              enabled: process.env.SSE_ENABLED === 'true',
              reconnectDelay: 5000
            }
          },
          logging: {
            enabled: true,
            browserLogs: true,
            serverLogs: true
          },
          integrations: {
            figma: {
              enabled: process.env.FIGMA_API_ENABLED === 'true'
            },
            jira: {
              enabled: process.env.JIRA_API_ENABLED === 'true'
            },
            storybook: {
              enabled: process.env.STORYBOOK_ENABLED === 'true'
            }
          },
          teams: {
            enabled: process.env.TEAMS_ENABLED === 'true'
          },
          mcp: {
            enabled: process.env.MCP_ENABLED === 'true',
            tools: [
              'dss-analyze-project',
              'dss-extract-tokens',
              'dss-generate-theme',
              'dss-audit-components'
            ]
          }
        },
        api: {
          baseUrl: process.env.API_BASE_URL || 'http://localhost:3001',
          timeout: 30000,
          rateLimitWindow: 900000,
          rateLimitMax: 100
        },
        ui: {
          adminUrl: process.env.ADMIN_UI_URL || 'http://localhost:5173',
          locale: 'en-US',
          theme: 'light'
        }
      }
    };

    res.status(200).json(config);
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/config/resolved/:projectId
 * Get fully resolved configuration (System > Project > User)
 */
router.get('/resolved/:projectId', authenticateToken, async (req, res, next) => {
  try {
    const { projectId } = req.params;

    // Verify project access
    const project = await Project.findByPk(projectId);
    if (!project) {
      return res.status(404).json({ status: 'error', message: 'Project not found' });
    }

    const resolved = await ConfigService.resolveConfig(projectId, req.user.id);

    res.json({
      status: 'success',
      data: resolved
    });
  } catch (error) {
    next(error);
  }
});

/**
 * GET /api/config/user
 * Get user-level preferences
 */
router.get('/user', authenticateToken, async (req, res, next) => {
  try {
    const config = await ConfigService.getScopeConfig('USER', req.user.id);

    res.json({
      status: 'success',
      data: config
    });
  } catch (error) {
    next(error);
  }
});

/**
 * PUT /api/config/user
 * Update user-level preferences
 */
router.put('/user', authenticateToken, async (req, res, next) => {
  try {
    const { key, value } = req.body;

    if (!key || value === undefined) {
      return res.status(400).json({
        status: 'error',
        message: 'Key and value are required'
      });
    }

    const result = await ConfigService.setConfig({
      scope: 'USER',
      scopeId: req.user.id,
      key,
      value,
      actorId: req.user.id
    });

    res.json({
      status: 'success',
      message: 'User preference updated',
      data: result
    });
  } catch (error) {
    next(error);
  }
});

export default router;
