import express from 'express';

import { getUserPreference, setUserPreference } from '../utils/settings.js';

const router = express.Router();

// GET /api/user-preferences/:key - Get a user preference for the logged-in user
router.get('/:key', async(req, res) =>
{
  const { key } = req.params;
  const userId = req.session?.loggedInUserId;
  if (!userId)
  {
    return res.status(401).json({ error: 'Not authenticated' });
  }
  try
  {
    const value = await getUserPreference(userId, key);
    if (typeof value === 'undefined' || value === null)
    {
      return res.status(404).json({ error: `Preference '${key}' not found for user` });
    }
    res.status(200).json({ key, value });
  }
  catch (err)
  {
    handlePrismaError(res, err, `fetch user preference '${key}'`);
  }
});

// PUT /api/user-preferences/:key - Set a user preference for the logged-in user
router.put('/:key', async(req, res) =>
{
  const { key } = req.params;
  const { value } = req.body;
  const userId = req.session?.loggedInUserId;
  if (!userId)
  {
    return res.status(401).json({ error: 'Not authenticated' });
  }
  if (typeof value === 'undefined')
  {
    return res.status(400).json({ error: 'Preference value is required in the request body' });
  }
  try
  {
    await setUserPreference(userId, key, value);
    res.status(200).json({ message: `Preference '${key}' updated for user` });
  }
  catch (err)
  {
    handlePrismaError(res, err, `update user preference '${key}'`);
  }
});


export default router;