const express = require('express');
const router = express.Router();
const db = require('../config/database');

/**
 * GET /api/settings/app
 * Fetch app-wide settings (public endpoint - no auth required)
 * Returns settings like update_available flag
 */
router.get('/app', async (req, res) => {
  try {
    const [settings] = await db.execute(
      'SELECT setting_key, setting_value FROM app_settings WHERE setting_key IN (?, ?, ?, ?)',
      ['update_available', 'min_app_version', 'update_message', 'update_url']
    );

    // Convert array to object for easier consumption
    const settingsObject = settings.reduce((acc, setting) => {
      acc[setting.setting_key] = setting.setting_value;
      return acc;
    }, {});

    // Parse boolean values
    if (settingsObject.update_available) {
      settingsObject.update_available = settingsObject.update_available === 'true';
    }

    res.json({
      success: true,
      settings: settingsObject
    });
  } catch (error) {
    console.error('Error fetching app settings:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to fetch app settings',
      error: error.message
    });
  }
});

/**
 * PUT /api/settings/app/:key
 * Update a specific app setting (admin only)
 */
router.put('/app/:key', async (req, res) => {
  try {
    const { key } = req.params;
    const { value } = req.body;

    if (!value) {
      return res.status(400).json({
        success: false,
        message: 'Setting value is required'
      });
    }

    const [result] = await db.execute(
      'UPDATE app_settings SET setting_value = ?, updated_at = NOW() WHERE setting_key = ?',
      [value, key]
    );

    if (result.affectedRows === 0) {
      return res.status(404).json({
        success: false,
        message: 'Setting not found'
      });
    }

    res.json({
      success: true,
      message: `Setting ${key} updated successfully`,
      setting: {
        key,
        value
      }
    });
  } catch (error) {
    console.error('Error updating app setting:', error);
    res.status(500).json({
      success: false,
      message: 'Failed to update app setting',
      error: error.message
    });
  }
});

module.exports = router;
