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();

/**
 * 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' });
    }

    // Note: We allow any authenticated user to view config if they are on the team
    // For now, simple check if project exists is sufficient for MVP,
    // or strictly check ownership/team membership if RBAC allows.
    // Assuming basic check for now:

    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;
