const asyncHandler = require('../middleware/async');
const WebSettings = require('../models/WebSettings');
const ErrorResponse = require('../utils/errorResponse');

// @desc    Get web settings
// @route   GET /api/web-settings
// @access  Private/Admin
exports.getSettings = asyncHandler(async (req, res, next) => {
  const settings = await WebSettings.getSettings();
  
  res.status(200).json({
    success: true,
    data: settings
  });
});

// @desc    Update web settings
// @route   PUT /api/web-settings
// @access  Private/Admin
exports.updateSettings = asyncHandler(async (req, res, next) => {
  try {
    console.log('=== Received update request ===');
    console.log('Request body:', JSON.stringify(req.body, null, 2));
    
    // All fields that can be updated
    const allowedUpdates = [
      // Site settings
      'siteName', 'siteUrl', 'siteEmail', 'sitePhone', 'siteAddress', 'siteDescription',
      
      // Store settings (both siteStore* and store* for backward compatibility)
      'siteStoreName', 'siteStoreEmail', 'siteStorePhone', 'siteStoreAddress', 'siteStoreCountry',
      'siteStoreState', 'siteStoreCity', 'siteStoreZipCode', 'siteStoreCurrency', 'siteStoreCurrencySymbol',
      'siteStoreTimezone', 'siteStoreLanguage', 'siteStoreLogo', 'siteStoreIcon', 'siteStoreMetaTitle',
      'siteStoreMetaDescription', 'siteStoreMetaKeywords',
      
      // Legacy store fields (for backward compatibility)
      'storeName', 'storeEmail', 'storePhone', 'storeAddress', 'storeCountry',
      'storeState', 'storeCity', 'storeZipCode', 'storeCurrency', 'storeCurrencySymbol',
      'storeTimezone', 'storeLanguage', 'storeLogo', 'storeIcon', 'storeMetaTitle',
      'storeMetaDescription', 'storeMetaKeywords',
      
      // Other settings
      'maintenanceMode', 'allowRegistration', 'enableEmailVerification', 'defaultUserRole',
      'timezone', 'dateFormat', 'timeFormat', 'currency', 'currencySymbol',
      'currencyPosition', 'thousandSeparator', 'decimalSeparator', 'numberOfDecimals'
    ];
    
    const updates = {};
    const ignoredFields = [];
    
    console.log('Processing request body fields:');
    
    // Convert all boolean strings to actual booleans
    const processedBody = { ...req.body };
    Object.keys(processedBody).forEach(key => {
      if (processedBody[key] === 'true') processedBody[key] = true;
      if (processedBody[key] === 'false') processedBody[key] = false;
    });
    
    // Directly use the field names as they come from the frontend
    Object.keys(processedBody).forEach(key => {
      if (allowedUpdates.includes(key)) {
        updates[key] = processedBody[key];
        console.log(`  - Including field: ${key} = ${JSON.stringify(processedBody[key])} (type: ${typeof processedBody[key]})`);
      } else {
        ignoredFields.push(key);
        console.log(`  - Ignoring field (not in allowedUpdates): ${key}`);
      }
    });

    if (ignoredFields.length > 0) {
      console.log(`Ignored fields: ${ignoredFields.join(', ')}`);
    }

    console.log('Final updates object:', JSON.stringify(updates, null, 2));
    
    console.log('Calling WebSettings.updateSettings()...');
    const settings = await WebSettings.updateSettings(updates);
    
    console.log('Settings updated successfully:', JSON.stringify(settings, null, 2));
    console.log('Maintenance mode is now:', settings.maintenanceMode);

    res.status(200).json({
      success: true,
      data: settings
    });
  } catch (error) {
    console.error('Error in updateSettings:', error);
    console.error('Error stack:', error.stack);
    next(error);
  }
});

// Middleware to get settings and attach to request
// This can be used in other routes that need access to settings
exports.getSettingsMiddleware = asyncHandler(async (req, res, next) => {
  const settings = await WebSettings.getSettings();
  req.app.locals.settings = settings;
  next();
});

// Middleware to check if maintenance mode is enabled
exports.checkMaintenanceMode = asyncHandler(async (req, res, next) => {
  const path = req.path;
  
  // Define routes that should bypass maintenance mode
  const bypassRoutes = [
    // Admin routes
    path.startsWith('/api/admin'),
    path.startsWith('/admin'),
    // Web settings API - allow all methods
    path.startsWith('/api/web-settings'),
    path.startsWith('/api/v1/web-settings'),
    // API docs
    path.startsWith('/api-docs'),
    // Health check endpoint
    path === '/health' || path === '/health/'
  ];
  
  // If any bypass condition is true, skip maintenance check
  if (bypassRoutes.some(condition => typeof condition === 'function' ? condition() : condition)) {
    console.log(`Skipping maintenance check for ${req.method} ${path}`);
    return next();
  }

  // Check maintenance mode for all other routes
  const settings = await WebSettings.getSettings();
  
  if (settings.maintenanceMode) {
    console.log(`Maintenance mode is active, blocking ${req.method} ${path}`);
    return next(new ErrorResponse('The site is currently under maintenance. Please check back later.', 503));
  }
  
  next();
});
