/**
 * adminSettingsRoutes.js - Global Settings Management API Endpoints
 * Purpose: CRUD operations for site-wide settings and configuration
 * Routes: 4 endpoints for settings management
 */

const express = require('express');
const router = express.Router();

// GET /api/admin/settings - Get all settings
router.get('/settings', async (req, res) => {
  try {
    const pool = req.app.locals.pool;

    const [settings] = await pool.execute(
      `SELECT setting_key, setting_value
       FROM site_settings
       ORDER BY setting_key ASC`
    );

    // Transform to object format
    const settingsObject = {};
    settings.forEach(setting => {
      try {
        // Try to parse JSON values
        settingsObject[setting.setting_key] = JSON.parse(setting.setting_value);
      } catch (e) {
        settingsObject[setting.setting_key] = setting.setting_value;
      }
    });

    res.json({
      success: true,
      message: 'Settings retrieved successfully',
      data: settingsObject
    });
  } catch (error) {
    console.error('Settings fetch error:', error);
    res.status(500).json({
      success: false,
      error: 'Settings Error',
      message: error.message
    });
  }
});

// GET /api/admin/settings/:key - Get specific setting
router.get('/settings/:key', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const { key } = req.params;

    const [settings] = await pool.execute(
      'SELECT setting_key, setting_value FROM site_settings WHERE setting_key = ?',
      [key]
    );

    if (settings.length === 0) {
      return res.status(404).json({
        success: false,
        error: 'Not Found',
        message: 'Setting not found'
      });
    }

    try {
      const value = JSON.parse(settings[0].setting_value);
      settings[0].setting_value = value;
    } catch (e) {
      // Keep as string if not JSON
    }

    res.json({
      success: true,
      message: 'Setting retrieved successfully',
      data: settings[0]
    });
  } catch (error) {
    console.error('Setting fetch error:', error);
    res.status(500).json({
      success: false,
      error: 'Settings Error',
      message: error.message
    });
  }
});

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

    // Validate input
    if (value === undefined || value === null) {
      return res.status(400).json({
        success: false,
        error: 'Validation Error',
        message: 'value is required'
      });
    }

    // Convert value to JSON string if object
    let settingValue = typeof value === 'object' ? JSON.stringify(value) : String(value);

    // Check if setting exists
    const [existing] = await pool.execute(
      'SELECT setting_key FROM site_settings WHERE setting_key = ?',
      [key]
    );

    if (existing.length === 0) {
      // Create new setting
      await pool.execute(
        `INSERT INTO site_settings (setting_key, setting_value, created_at)
         VALUES (?, ?, NOW())`,
        [key, settingValue]
      );
    } else {
      // Update existing setting
      await pool.execute(
        `UPDATE site_settings SET setting_value = ?, updated_at = NOW()
         WHERE setting_key = ?`,
        [settingValue, key]
      );
    }

    res.json({
      success: true,
      message: 'Setting updated successfully',
      data: { key, value }
    });
  } catch (error) {
    console.error('Setting update error:', error);
    res.status(500).json({
      success: false,
      error: 'Update Error',
      message: error.message
    });
  }
});

// PUT /api/admin/settings - Update multiple settings at once
router.put('/settings', async (req, res) => {
  try {
    const pool = req.app.locals.pool;
    const settings = req.body;

    if (!settings || typeof settings !== 'object') {
      return res.status(400).json({
        success: false,
        error: 'Validation Error',
        message: 'Request body must be an object with settings'
      });
    }

    const updates = [];
    const errors = [];

    // Process each setting
    for (const [key, value] of Object.entries(settings)) {
      try {
        const settingValue = typeof value === 'object' ? JSON.stringify(value) : String(value);

        // Check if setting exists
        const [existing] = await pool.execute(
          'SELECT setting_key FROM site_settings WHERE setting_key = ?',
          [key]
        );

        if (existing.length === 0) {
          // Create new setting
          await pool.execute(
            `INSERT INTO site_settings (setting_key, setting_value, created_at)
             VALUES (?, ?, NOW())`,
            [key, settingValue]
          );
        } else {
          // Update existing setting
          await pool.execute(
            `UPDATE site_settings SET setting_value = ?, updated_at = NOW()
             WHERE setting_key = ?`,
            [settingValue, key]
          );
        }

        updates.push(key);
      } catch (error) {
        errors.push({ key, error: error.message });
      }
    }

    res.json({
      success: errors.length === 0,
      message: `Updated ${updates.length} settings`,
      data: {
        updated: updates,
        errors: errors
      }
    });
  } catch (error) {
    console.error('Bulk settings update error:', error);
    res.status(500).json({
      success: false,
      error: 'Update Error',
      message: error.message
    });
  }
});

// GET /api/admin/settings-categories - Get settings organized by category
router.get('/settings-categories', async (req, res) => {
  try {
    const pool = req.app.locals.pool;

    const settings = {
      site: {
        site_name: 'WakaTraffic',
        site_url: 'https://wakatraffic.ng',
        description: 'Social Media Marketing Services'
      },
      brand: {
        primary_color: '#3498db',
        secondary_color: '#2c3e50',
        logo_url: '/images/logo.png',
        favicon_url: '/images/favicon.ico'
      },
      currency: {
        currency_code: 'NGN',
        currency_symbol: '₦',
        decimal_places: 2
      },
      timezone: {
        timezone: 'Africa/Lagos',
        date_format: 'DD/MM/YYYY',
        time_format: '24H'
      },
      verification: {
        email_verification_required: true,
        phone_verification_required: false,
        kyc_verification_required: false
      },
      limits: {
        min_order_amount: 100,
        max_order_amount: 1000000,
        daily_withdrawal_limit: 500000,
        monthly_withdrawal_limit: 10000000
      },
      notifications: {
        send_order_confirmation: true,
        send_payment_confirmation: true,
        send_order_updates: true,
        send_promotional_emails: false
      }
    };

    res.json({
      success: true,
      message: 'Settings categories retrieved successfully',
      data: settings
    });
  } catch (error) {
    console.error('Settings categories error:', error);
    res.status(500).json({
      success: false,
      error: 'Settings Error',
      message: error.message
    });
  }
});

module.exports = router;
