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

const router = express.Router();

/**
 * GET /api/admin/config/system
 * Get all system-level configuration
 */
router.get('/system',
  authenticateToken,
  authorizeRole(['admin']),
  async (req, res, next) => {
    try {
      const config = await ConfigService.getScopeConfig('SYSTEM', null);

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

/**
 * PUT /api/admin/config/system
 * Update system-level configuration
 */
router.put('/system',
  authenticateToken,
  authorizeRole(['admin']),
  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: 'SYSTEM',
        scopeId: null,
        key,
        value,
        actorId: req.user.id
      });

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

/**
 * GET /api/admin/config/project/:projectId
 * Get project-level configuration
 */
router.get('/project/:projectId',
  authenticateToken,
  // Admin or project owner access logic
  async (req, res, next) => {
    try {
      const { projectId } = req.params;

      // Access Check
      if (req.user.role !== 'admin') {
        const project = await Project.findOne({ where: { id: projectId, userId: req.user.id } });
        if (!project) {
          return res.status(403).json({ status: 'error', message: 'Forbidden' });
        }
      }

      const config = await ConfigService.getScopeConfig('PROJECT', projectId);

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

/**
 * PUT /api/admin/config/project/:projectId
 * Update project-level configuration
 */
router.put('/project/:projectId',
  authenticateToken,
  async (req, res, next) => {
    try {
      const { projectId } = req.params;
      const { key, value } = req.body;

      // Access Check
      if (req.user.role !== 'admin') {
        const project = await Project.findOne({ where: { id: projectId, userId: req.user.id } });
        if (!project) {
          return res.status(403).json({ status: 'error', message: 'Forbidden' });
        }
      }

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

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

export default router;
