import express from 'express';
import { getSetting, setSetting, getUserPreference, setUserPreference } from '../utils/settings.js';
import { handlePrismaError } from '../database.js';

const router = express.Router();


// --- Settings API --- //

// GET /api/settings/:key - Get a specific setting value
router.get('/:key', async(req, res) =>
{
  const { key } = req.params;
  try
  {
    const setting = await getSetting(key);
    if (!setting)
    {
      return res.status(404).json({ error: `Setting '${key}' not found` });
    }
    res.status(200).json(setting);
  }
  catch (err)
  {
    handlePrismaError(res, err, `fetch setting '${key}'`);
  }
});

// PUT /api/settings/:key - Update or create a specific setting
router.put('/:key', async(req, res) =>
{
  const { key } = req.params;
  const { value } = req.body;

  if (typeof value === 'undefined')
  {
    return res.status(400).json({ error: 'Setting value is required in the request body' });
  }

  try
  {
    await setSetting(key, value);
    res.status(200).json({ message: `Setting '${key}' updated successfully` });
  }
  catch (err)
  {
    handlePrismaError(res, err, `update setting '${key}'`);
  }
});

export default router;