// ============================================================
// USER PREFERENCES — STT model & TTS voice selection
// ============================================================

var express = require('express');
var router = express.Router();
var db = require('../db/database');
var { authMiddleware } = require('../middleware/auth');
var { getSTTModelLists, getSTTProvider } = require('../utils/sttProvider');
var { getLiteLLMTTSVoicesForModel, getTTSProvider } = require('../utils/ttsProvider');

router.use(authMiddleware);

// Get current user's STT/TTS preferences
router.get('/preferences', async function(req, res) {
  try {
    var user = await db.get('SELECT stt_model, tts_voice FROM users WHERE id = ?', [req.user.id]);
    res.json({
      success: true,
      stt_model: user?.stt_model || null,
      tts_voice: user?.tts_voice || null
    });
  } catch (err) {
    console.error('[Preferences]', err.message);
    res.status(500).json({ error: 'Request failed' });
  }
});

// Update user's STT/TTS preferences
router.post('/preferences', async function(req, res) {
  try {
    var { stt_model, tts_voice } = req.body;

    await db.run(
      'UPDATE users SET stt_model = ?, tts_voice = ? WHERE id = ?',
      [stt_model || null, tts_voice || null, req.user.id]
    );

    res.json({ success: true });
  } catch (err) {
    console.error('[Preferences]', err.message);
    res.status(500).json({ error: 'Request failed' });
  }
});

// Get available STT models and TTS voices
router.get('/preferences/options', async function(req, res) {
  try {
    var provider = getSTTProvider();
    var ttsProvider = getTTSProvider();

    var dbModel = await db.getSetting('tts.model') || '';
    var dbVoice = await db.getSetting('tts.voice') || '';
    var ttsModel = dbModel || process.env.LITELLM_TTS_MODEL || '';
    var sttModels = getSTTModelLists().litellm.map(function(model) { return { value: model, label: model }; });
    var ttsVoices = getLiteLLMTTSVoicesForModel(ttsModel, { currentVoice: dbVoice }).map(function(voice) { return { value: voice, label: voice }; });

    res.json({
      success: true,
      sttProvider: provider || 'none',
      sttModels: sttModels,
      ttsProvider: ttsProvider || 'browser',
      ttsModel: ttsModel || null,
      ttsVoices: ttsVoices
    });

  } catch (err) {
    console.error('[Preferences]', err.message);
    res.status(500).json({ error: 'Request failed' });
  }
});

module.exports = router;
