import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import compression from 'compression';
import { RateLimiterMemory } from 'rate-limiter-flexible';
import { LicenseManager } from '../licensing/licenseManager.js';
import { DigitalOceanClient } from '../licensing/digitalOceanClient.js';
import { ErrorHandlingManager } from '../resilience/errorHandlingManager.js';
import { ResilienceOrchestrator } from '../resilience/resilienceOrchestrator.js';
import { CodeQualityManager } from '../quality/codeQualityManager.js';
import { AdvancedTestingFramework } from '../testing/advancedTestingFramework.js';
import { CodeQualityManager } from '../quality/codeQualityManager.js';
import { AdvancedTestingFramework } from '../testing/advancedTestingFramework.js';
import { createHash } from 'crypto';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

/**
 * ZAI Web Server
 * Handles admin dashboard, user management, and PayPal integration
 */
export class ZAIWebServer {
  constructor() {
    this.app = express();
    this.port = process.env.PORT || 3000;
    this.licenseManager = new LicenseManager();
    this.digitalOcean = new DigitalOceanClient();
    this.errorHandler = new ErrorHandlingManager();
    this.resilienceOrchestrator = new ResilienceOrchestrator();
    this.codeQualityManager = new CodeQualityManager();
    this.testingFramework = new AdvancedTestingFramework();
    this.codeQualityManager = new CodeQualityManager();
    this.testingFramework = new AdvancedTestingFramework();
    this.demoMode = false;
    this.demoLicenses = []; // Store demo licenses in memory
    
    // Rate limiting
    this.rateLimiter = new RateLimiterMemory({
      keyGenerator: (req) => req.ip,
      points: 100, // Number of requests
      duration: 60, // Per 60 seconds
    });

    this.adminRateLimiter = new RateLimiterMemory({
      keyGenerator: (req) => req.ip,
      points: 20, // Stricter for admin
      duration: 60,
    });

    this.setupMiddleware();
    this.setupRoutes();
    
    console.log('🌐 ZAI Web Server initialized');
  }

  /**
   * Setup Express middleware
   */
  setupMiddleware() {
    // Security
    this.app.use(helmet({
      contentSecurityPolicy: {
        directives: {
          defaultSrc: ["'self'"],
          styleSrc: ["'self'", "'unsafe-inline'", "https://cdnjs.cloudflare.com"],
          scriptSrc: ["'self'", "https://www.paypal.com", "https://js.stripe.com"],
          imgSrc: ["'self'", "data:", "https:"],
          connectSrc: ["'self'", "https://api.paypal.com"]
        }
      }
    }));

    // CORS
    this.app.use(cors({
      origin: process.env.NODE_ENV === 'production' 
        ? ['https://yourdomain.com'] 
        : ['http://localhost:3000', 'http://127.0.0.1:3000'],
      credentials: true
    }));

    // Compression
    this.app.use(compression());

    // Body parsing
    this.app.use(express.json({ limit: '10mb' }));
    this.app.use(express.urlencoded({ extended: true, limit: '10mb' }));

    // Static files
    this.app.use(express.static(path.join(__dirname, '../../website/static')));

    // Rate limiting middleware
    this.app.use(async (req, res, next) => {
      try {
        await this.rateLimiter.consume(req.ip);
        next();
      } catch (rejRes) {
        res.status(429).json({ error: 'Too many requests' });
      }
    });
  }

  /**
   * Setup API routes
   */
  setupRoutes() {
    // Health check
    this.app.get('/health', (req, res) => {
      res.json({
        status: 'healthy',
        timestamp: new Date().toISOString(),
        version: '1.0.0'
      });
    });

    // Code quality endpoints
    this.app.get('/api/quality/stats', async (req, res) => {
      try {
        const qualityStats = this.codeQualityManager.getQualityStats();
        res.json(qualityStats);
      } catch (error) {
        const errorInfo = await this.errorHandler.handleError(error, {
          service: 'quality-service',
          operation: 'get_quality_stats'
        });
        res.status(500).json({ error: error.message, errorId: errorInfo.id });
      }
    });

    this.app.post('/api/quality/analyze', async (req, res) => {
      try {
        const { filePath, sourceCode } = req.body;
        const analysis = await this.codeQualityManager.analyzeCodeQuality(filePath, sourceCode);
        res.json(analysis);
      } catch (error) {
        const errorInfo = await this.errorHandler.handleError(error, {
          service: 'quality-service',
          operation: 'analyze_code'
        });
        res.status(500).json({ error: error.message, errorId: errorInfo.id });
      }
    });

    // Testing endpoints
    this.app.get('/api/testing/stats', async (req, res) => {
      try {
        const testingStats = this.testingFramework.getTestingStats();
        res.json(testingStats);
      } catch (error) {
        const errorInfo = await this.errorHandler.handleError(error, {
          service: 'testing-service',
          operation: 'get_testing_stats'
        });
        res.status(500).json({ error: error.message, errorId: errorInfo.id });
      }
    });

    this.app.post('/api/testing/run/:suiteName', async (req, res) => {
      try {
        const { suiteName } = req.params;
        const options = req.body || {};
        const testResult = await this.testingFramework.runTestSuite(suiteName, options);
        res.json(testResult);
      } catch (error) {
        const errorInfo = await this.errorHandler.handleError(error, {
          service: 'testing-service',
          operation: 'run_test_suite'
        });
        res.status(500).json({ error: error.message, errorId: errorInfo.id });
      }
    });

    this.app.post('/api/testing/generate-ai-tests', async (req, res) => {
      try {
        const { sourceCode, testType } = req.body;
        const aiTests = await this.testingFramework.generateAITests(sourceCode, testType);
        res.json(aiTests);
      } catch (error) {
        const errorInfo = await this.errorHandler.handleError(error, {
          service: 'testing-service',
          operation: 'generate_ai_tests'
        });
        res.status(500).json({ error: error.message, errorId: errorInfo.id });
      }
    });

    // Main website routes
    this.app.get('/', (req, res) => {
      res.sendFile(path.join(__dirname, '../../website/static/index.html'));
    });

    this.app.get('/pricing', (req, res) => {
      res.sendFile(path.join(__dirname, '../../website/static/pricing.html'));
    });

    this.app.get('/download', (req, res) => {
      res.sendFile(path.join(__dirname, '../../website/static/download.html'));
    });

    this.app.get('/admin', (req, res) => {
      res.sendFile(path.join(__dirname, '../../website/static/admin.html'));
    });

    this.app.get('/admin-simple', (req, res) => {
      res.sendFile(path.join(__dirname, '../../website/static/admin-simple.html'));
    });

    this.app.get('/dashboard', (req, res) => {
      res.sendFile(path.join(__dirname, '../../website/static/dashboard.html'));
    });

    this.app.get('/analytics', (req, res) => {
      res.sendFile(path.join(__dirname, '../../website/static/analytics-dashboard.html'));
    });

    this.app.get('/customer-portal', (req, res) => {
      res.sendFile(path.join(__dirname, '../../website/static/customer-portal.html'));
    });

    // API routes
    this.app.use('/api', this.createAPIRouter());
    
    // Admin routes (with stricter rate limiting)
    this.app.use('/admin', this.createAdminRateLimiter(), this.createAdminRouter());
    
    // User dashboard routes
    this.app.use('/dashboard', this.createDashboardRouter());

    // PayPal webhook
    this.app.post('/webhook/paypal', this.handlePayPalWebhook.bind(this));

    // 404 handler
    this.app.use((req, res) => {
      res.status(404).json({ error: 'Not found' });
    });

    // Enhanced error handler with resilience
    this.app.use(async (err, req, res, next) => {
      try {
        // Handle error with resilience system
        const errorInfo = await this.errorHandler.handleError(err, {
          service: 'web-server',
          operation: req.method + ' ' + req.path,
          userId: req.user?.userId,
          requestId: req.headers['x-request-id']
        });

        // Orchestrate resilience response if needed
        if (errorInfo.classification.severity === 'CRITICAL') {
          await this.resilienceOrchestrator.orchestrateResilience({
            type: 'service_error',
            service: 'web-server',
            error: err,
            severity: errorInfo.classification.severity
          });
        }

        console.error('Server error handled:', errorInfo.id);

        // Return appropriate error response
        const statusCode = this.getErrorStatusCode(err, errorInfo);
        res.status(statusCode).json({
          error: 'Internal server error',
          errorId: errorInfo.id,
          recovered: errorInfo.recovered
        });

      } catch (handlingError) {
        console.error('Error handling failed:', handlingError);
        res.status(500).json({ error: 'Internal server error' });
      }
    });
  }

  /**
   * Create API router
   */
  createAPIRouter() {
    const router = express.Router();

    // License validation with enhanced error handling
    router.post('/license/validate', async (req, res) => {
      try {
        const { token } = req.body;
        const validation = await this.licenseManager.validateLicense(token);
        res.json(validation);
      } catch (error) {
        const errorInfo = await this.errorHandler.handleError(error, {
          service: 'license-service',
          operation: 'validate_license',
          requestId: req.headers['x-request-id']
        });

        const statusCode = this.getErrorStatusCode(error, errorInfo);
        res.status(statusCode).json({
          error: error.message,
          errorId: errorInfo.id,
          recovered: errorInfo.recovered
        });
      }
    });

    // License generation (for payment processing)
    router.post('/license/generate', async (req, res) => {
      try {
        const licenseData = req.body;
        const license = await this.licenseManager.generateLicense(licenseData);
        res.json({ 
          success: true, 
          licenseId: license.licenseId,
          token: license.token 
        });
      } catch (error) {
        res.status(400).json({ error: error.message });
      }
    });

    // Get license tiers
    router.get('/license/tiers', (req, res) => {
      res.json(this.licenseManager.licenseTiers);
    });

    // Device management
    router.post('/device/register', async (req, res) => {
      try {
        const { licenseToken, deviceFingerprint } = req.body;
        // Implementation for device registration
        res.json({ success: true });
      } catch (error) {
        res.status(400).json({ error: error.message });
      }
    });

    return router;
  }

  /**
   * Create admin router
   */
  createAdminRouter() {
    const router = express.Router();

    // Admin authentication middleware
    router.use(this.authenticateAdmin.bind(this));

    // Get all licenses
    router.get('/licenses', async (req, res) => {
      try {
        const licenses = await this.getAllLicenses();
        res.json(licenses);
      } catch (error) {
        // Return demo data if in demo mode
        if (this.demoMode) {
          res.json(this.getDemoLicenses());
        } else {
          res.status(500).json({ error: error.message });
        }
      }
    });

    // Generate new license
    router.post('/licenses/generate', async (req, res) => {
      try {
        const licenseData = req.body;
        const license = await this.generateAdminLicense(licenseData);
        res.json(license);
      } catch (error) {
        res.status(400).json({ error: error.message });
      }
    });

    // Delete license
    router.delete('/licenses/:licenseId', async (req, res) => {
      try {
        const result = await this.deleteLicense(req.params.licenseId);
        res.json(result);
      } catch (error) {
        res.status(400).json({ error: error.message });
      }
    });

    // Get license token
    router.get('/licenses/:licenseId/token', async (req, res) => {
      try {
        const token = await this.getLicenseToken(req.params.licenseId);
        res.json({ token });
      } catch (error) {
        res.status(400).json({ error: error.message });
      }
    });

    // Get all users
    router.get('/users', async (req, res) => {
      try {
        const users = await this.getAllUsers();
        res.json(users);
      } catch (error) {
        // Return demo data if in demo mode
        if (this.demoMode) {
          res.json(this.getDemoUsers());
        } else {
          res.status(500).json({ error: error.message });
        }
      }
    });

    // Get user details
    router.get('/users/:userId', async (req, res) => {
      try {
        const user = await this.getUserDetails(req.params.userId);
        res.json(user);
      } catch (error) {
        res.status(404).json({ error: error.message });
      }
    });

    // Remove device from license
    router.delete('/users/:userId/devices/:deviceId', async (req, res) => {
      try {
        const { userId, deviceId } = req.params;
        const result = await this.removeUserDevice(userId, deviceId);
        res.json(result);
      } catch (error) {
        res.status(400).json({ error: error.message });
      }
    });

    // Get analytics
    router.get('/analytics', async (req, res) => {
      try {
        const analytics = await this.digitalOcean.getAnalytics();
        res.json(analytics);
      } catch (error) {
        // Return demo analytics if in demo mode
        if (this.demoMode) {
          res.json(this.getDemoAnalytics());
        } else {
          res.status(500).json({ error: error.message });
        }
      }
    });

    // Get system stats
    router.get('/stats', async (req, res) => {
      try {
        const stats = await this.getSystemStats();
        res.json(stats);
      } catch (error) {
        // Return demo stats if in demo mode
        if (this.demoMode) {
          res.json(this.getDemoStats());
        } else {
          res.status(500).json({ error: error.message });
        }
      }
    });

    return router;
  }

  /**
   * Create user dashboard router
   */
  createDashboardRouter() {
    const router = express.Router();

    // User authentication middleware
    router.use(this.authenticateUser.bind(this));

    // Get user's devices
    router.get('/devices', async (req, res) => {
      try {
        const devices = await this.getUserDevices(req.user.licenseId);
        res.json(devices);
      } catch (error) {
        res.status(500).json({ error: error.message });
      }
    });

    // Remove user's device
    router.delete('/devices/:deviceId', async (req, res) => {
      try {
        const result = await this.licenseManager.removeDeviceFromLicense(
          req.user.licenseId, 
          req.params.deviceId
        );
        res.json({ success: true, device: result });
      } catch (error) {
        res.status(400).json({ error: error.message });
      }
    });

    // Get user's usage stats
    router.get('/usage', async (req, res) => {
      try {
        const usage = await this.getUserUsage(req.user.userId);
        res.json(usage);
      } catch (error) {
        res.status(500).json({ error: error.message });
      }
    });

    return router;
  }

  /**
   * Admin rate limiter middleware
   */
  createAdminRateLimiter() {
    return async (req, res, next) => {
      try {
        await this.adminRateLimiter.consume(req.ip);
        next();
      } catch (rejRes) {
        res.status(429).json({ error: 'Too many admin requests' });
      }
    };
  }

  /**
   * Admin authentication middleware
   */
  authenticateAdmin(req, res, next) {
    const adminKey = req.headers['x-admin-key'];
    const expectedKey = process.env.ADMIN_KEY || 'your-super-secret-admin-key';
    
    if (adminKey !== expectedKey) {
      return res.status(401).json({ error: 'Unauthorized' });
    }
    
    next();
  }

  /**
   * User authentication middleware
   */
  async authenticateUser(req, res, next) {
    try {
      const token = req.headers.authorization?.replace('Bearer ', '');
      
      if (!token) {
        return res.status(401).json({ error: 'No token provided' });
      }

      const validation = await this.licenseManager.validateLicense(token);
      
      if (!validation.isValid) {
        return res.status(401).json({ error: 'Invalid license' });
      }

      req.user = {
        userId: validation.license.userId,
        licenseId: validation.license.licenseId,
        tier: validation.license.tier
      };
      
      next();
    } catch (error) {
      res.status(401).json({ error: 'Authentication failed' });
    }
  }

  /**
   * Handle PayPal webhook
   */
  async handlePayPalWebhook(req, res) {
    try {
      const event = req.body;

      console.log('📧 PayPal webhook received:', event.event_type);
      console.log('📧 PayPal event data:', JSON.stringify(event, null, 2));

      if (event.event_type === 'PAYMENT.CAPTURE.COMPLETED') {
        await this.handlePaymentCompleted(event);
      }

      res.status(200).json({ received: true });
    } catch (error) {
      console.error('❌ PayPal webhook error:', error);
      res.status(400).json({ error: error.message });
    }
  }

  /**
   * Handle completed payment
   */
  async handlePaymentCompleted(event) {
    try {
      const payment = event.resource;
      console.log('💰 Processing payment:', payment.id);

      // Determine tier based on payment amount
      const amount = parseFloat(payment.amount?.value || 0);
      let tier = 'PERSONAL'; // Default

      if (amount >= 100) {
        tier = 'ENTERPRISE';
      } else if (amount >= 50) {
        tier = 'BUSINESS';
      } else if (amount >= 25) {
        tier = 'SMALL_TEAM';
      } else if (amount >= 5) {
        tier = 'PERSONAL';
      }

      console.log(`💰 Payment amount: $${amount} -> Tier: ${tier}`);

      // Extract user info from payment (if available)
      const payer = payment.payer || {};
      const userEmail = payer.email_address || 'customer@example.com';
      const userName = payer.name ?
        `${payer.name.given_name || ''} ${payer.name.surname || ''}`.trim() :
        'Customer';

      // Generate license
      let license;
      try {
        // Create license data
        const licenseId = 'ZAI-PAYPAL-' + Date.now();
        license = {
          licenseId,
          tier: tier,
          tierConfig: this.licenseManager.licenseTiers[tier],
          userId: 'paypal_' + payment.id,
          userEmail: userEmail,
          userName: userName,
          paymentId: payment.id,
          status: 'active',
          createdAt: new Date().toISOString(),
          expiresAt: null, // Lifetime
          devices: [],
          paypalGenerated: true
        };

        // Generate JWT token
        const token = this.licenseManager.generateJWT({
          licenseId: license.licenseId,
          tier: license.tier,
          userId: license.userId,
          maxDevices: license.tierConfig.maxDevices
        });

        license.token = token;

        // Store the license
        await this.digitalOcean.storeLicense(license);

        console.log('✅ PayPal license generated and stored:', licenseId);
      } catch (error) {
        console.error('❌ Failed to generate PayPal license:', error.message);

        // Fallback to demo mode if storage fails
        license = {
          licenseId: 'ZAI-PAYPAL-' + Date.now(),
          tier: tier,
          tierConfig: this.licenseManager.licenseTiers[tier],
          userId: 'paypal_' + payment.id,
          userEmail: userEmail,
          userName: userName,
          paymentId: payment.id,
          status: 'active',
          createdAt: new Date().toISOString(),
          expiresAt: null, // Lifetime
          devices: [],
          token: 'demo_paypal_token_' + payment.id,
          paypalGenerated: true
        };

        // Add to demo licenses array
        this.demoLicenses.push(license);
        console.log('⚠️ Fallback: Demo license created for PayPal payment');
      }

      console.log(`✅ License generated for payment: ${payment.id}`);
      console.log(`📧 License details:`, {
        licenseId: license.licenseId,
        tier: license.tier,
        userEmail: license.userEmail,
        userName: license.userName
      });

      // Store payment record
      await this.storePaymentRecord(payment, license);

      // TODO: Send license to user via email
      console.log('📧 License token (send to user):', license.token);

    } catch (error) {
      console.error('❌ Payment processing failed:', error);
    }
  }

  /**
   * Get appropriate HTTP status code for error
   */
  getErrorStatusCode(error, errorInfo) {
    // Check error code first
    if (error.code === 401 || error.message.includes('unauthorized')) {
      return 401;
    }
    if (error.code === 403 || error.message.includes('forbidden')) {
      return 403;
    }
    if (error.code === 404 || error.message.includes('not found')) {
      return 404;
    }
    if (error.code === 429 || error.message.includes('rate limit')) {
      return 429;
    }

    // Check error classification
    if (errorInfo?.classification) {
      switch (errorInfo.classification.severity) {
        case 'CRITICAL':
          return 503; // Service Unavailable
        case 'HIGH':
          return 500; // Internal Server Error
        case 'MEDIUM':
          return 400; // Bad Request
        default:
          return 500;
      }
    }

    return 500; // Default to Internal Server Error
  }

  /**
   * Setup resilience monitoring and event handlers
   */
  setupResilienceMonitoring() {
    // Listen for error recovery events
    this.errorHandler.on('errorRecovered', (errorInfo) => {
      console.log(`✅ Error recovered: ${errorInfo.id} in ${errorInfo.recoveryTime}ms`);
    });

    this.errorHandler.on('errorRecoveryFailed', (errorInfo) => {
      console.error(`❌ Error recovery failed: ${errorInfo.id}`);
    });

    // Listen for circuit breaker events
    this.errorHandler.on('circuitBreakerOpened', (event) => {
      console.warn(`🚨 Circuit breaker opened for service: ${event.serviceName}`);
    });

    // Listen for resilience orchestration events
    this.resilienceOrchestrator.on('resilienceOrchestrated', (orchestration) => {
      console.log(`🛡️ Resilience orchestrated: ${orchestration.id} (${orchestration.success ? 'SUCCESS' : 'FAILED'})`);
    });

    this.resilienceOrchestrator.on('systemHealthChecked', (healthCheck) => {
      if (healthCheck.overallHealth !== 'HEALTHY') {
        console.warn(`⚠️ System health: ${healthCheck.overallHealth} (score: ${healthCheck.resilienceScore.toFixed(2)})`);
      }
    });

    // Listen for code quality events
    this.codeQualityManager.on('codeAnalysisCompleted', (analysis) => {
      if (analysis.overallScore < 0.8) {
        console.warn(`📊 Low code quality detected: ${analysis.filePath} (score: ${analysis.overallScore.toFixed(2)})`);
      }
    });

    this.codeQualityManager.on('qualityTrendsAnalyzed', (trends) => {
      console.log(`📊 Quality trends: ${trends.trend} (score: ${trends.overallScore.toFixed(2)})`);
    });

    // Listen for testing events
    this.testingFramework.on('testSuiteCompleted', (testRun) => {
      const status = testRun.status === 'passed' ? '✅' : '❌';
      console.log(`🧪 Test suite ${testRun.suiteName}: ${status} (${testRun.results.passed}/${testRun.results.total} passed)`);
    });

    this.testingFramework.on('aiTestsGenerated', (generation) => {
      console.log(`🤖 AI generated ${generation.generatedTests.length} tests (confidence: ${generation.confidence.toFixed(2)})`);
    });

    this.testingFramework.on('automatedTestsCompleted', (results) => {
      const passedSuites = results.filter(r => r.status === 'passed').length;
      console.log(`🤖 Automated tests completed: ${passedSuites}/${results.length} suites passed`);
    });

    console.log('🛡️ Resilience monitoring setup complete');
    console.log('📊 Code quality monitoring setup complete');
    console.log('🧪 Testing framework monitoring setup complete');
  }

  /**
   * Enhanced server startup with resilience monitoring
   */
  async start() {
    try {
      // Initialize license manager (with error handling)
      try {
        await this.licenseManager.initialize();
      } catch (error) {
        console.log('⚠️ License manager initialization failed - running in demo mode');
        this.demoMode = true;
      }

      // Start server
      this.server = this.app.listen(this.port, () => {
        console.log(`🚀 ZAI Web Server running on port ${this.port}`);
        console.log(`📊 Admin dashboard: http://localhost:${this.port}/admin`);
        console.log(`👤 User dashboard: http://localhost:${this.port}/dashboard`);
        console.log(`🛡️ Enhanced error handling and resilience active`);

        if (this.demoMode) {
          console.log('⚠️ Running in demo mode - some features may be limited');
        }

        // Set up resilience monitoring
        this.setupResilienceMonitoring();
      });

      return this.server;
    } catch (error) {
      console.error('❌ Failed to start server:', error);
      throw error;
    }
  }

  /**
   * Stop the server
   */
  async stop() {
    if (this.server) {
      this.server.close();
      console.log('🛑 ZAI Web Server stopped');
    }
  }

  // Helper methods for admin functionality
  async getAllLicenses() {
    try {
      // Get licenses from DigitalOcean Spaces or local storage
      const licenses = await this.digitalOcean.getAllLicenses();

      // If no licenses found and in demo mode, return demo licenses
      if (licenses.length === 0 && this.demoMode) {
        return this.getDemoLicenses();
      }

      return licenses;
    } catch (error) {
      console.error('❌ Failed to get licenses:', error.message);

      // Fallback to demo licenses if everything fails
      if (this.demoMode) {
        return this.getDemoLicenses();
      }

      throw error;
    }
  }

  async generateAdminLicense(licenseData) {
    try {
      // Generate device fingerprint for admin-created licenses
      await this.licenseManager.deviceFingerprint.generateFingerprint();

      const license = await this.licenseManager.generateLicense({
        tier: licenseData.tier,
        userId: 'admin_' + Date.now(),
        userEmail: licenseData.userEmail,
        userName: licenseData.userName,
        paymentId: 'admin_generated_' + Date.now(),
        deviceFingerprint: this.licenseManager.deviceFingerprint.exportFingerprint(),
        adminGenerated: true,
        notes: licenseData.notes
      });

      return {
        licenseId: license.licenseId,
        userName: license.userName,
        userEmail: license.userEmail,
        tier: license.tier,
        maxDevices: license.tierConfig.maxDevices,
        token: license.token
      };
    } catch (error) {
      console.error('Admin license generation failed:', error);
      throw error;
    }
  }

  async deleteLicense(licenseId) {
    try {
      // In demo mode, just return success
      if (this.demoMode) {
        return { success: true, message: 'License deleted (demo mode)' };
      }

      // Use DigitalOcean client's delete method (which handles local storage fallback)
      const result = await this.digitalOcean.deleteLicense(licenseId);

      // Also remove from demo licenses if in demo mode
      if (this.demoMode) {
        this.demoLicenses = this.demoLicenses.filter(license => license.licenseId !== licenseId);
      }

      return result;
    } catch (error) {
      console.error('License deletion failed:', error);
      throw error;
    }
  }

  async getLicenseToken(licenseId) {
    try {
      // First try to get from stored licenses
      const licenses = await this.getAllLicenses();
      const license = licenses.find(l => l.licenseId === licenseId);

      if (license && license.token) {
        return license.token;
      }

      // Fallback for demo mode
      if (this.demoMode) {
        return 'demo_token_' + licenseId;
      }

      throw new Error('License not found or token not available');
    } catch (error) {
      console.error('Failed to get license token:', error);
      throw error;
    }
  }

  async getAllUsers() {
    // Implementation to get all users from DigitalOcean Spaces
    return [];
  }

  async getUserDetails(userId) {
    // Implementation to get user details
    return {};
  }

  async removeUserDevice(userId, deviceId) {
    // Implementation to remove device
    return {};
  }

  async getSystemStats() {
    // Implementation to get system statistics
    return {};
  }

  async getUserDevices(licenseId) {
    // Implementation to get user devices
    return [];
  }

  async getUserUsage(userId) {
    // Implementation to get user usage
    return {};
  }

  async storePaymentRecord(payment, license) {
    try {
      const paymentRecord = {
        paymentId: payment.id,
        licenseId: license.licenseId,
        amount: payment.amount?.value,
        currency: payment.amount?.currency_code,
        tier: license.tier,
        userEmail: license.userEmail,
        userName: license.userName,
        paymentDate: new Date().toISOString(),
        status: 'completed'
      };

      // Store in DigitalOcean Spaces
      if (!this.demoMode) {
        await this.digitalOcean.uploadData(
          `payments/${payment.id}.json`,
          paymentRecord
        );
      }

      console.log('💾 Payment record stored:', payment.id);
    } catch (error) {
      console.error('❌ Failed to store payment record:', error);
    }
  }

  // Demo data methods for testing
  getDemoUsers() {
    return [
      {
        userId: 'demo_user_1',
        userName: 'John Doe',
        userEmail: 'john@example.com',
        tier: 'PERSONAL',
        status: 'active',
        createdAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
        devices: [
          {
            deviceId: 'device_123',
            deviceName: 'John\'s MacBook Pro',
            active: true,
            lastSeen: new Date().toISOString(),
            registeredAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString()
          }
        ],
        usage: {
          totalSessions: 25,
          totalConversations: 150,
          totalMessages: 750,
          lastUsed: new Date().toISOString()
        }
      },
      {
        userId: 'demo_user_2',
        userName: 'Jane Smith',
        userEmail: 'jane@company.com',
        tier: 'SMALL_TEAM',
        status: 'active',
        createdAt: new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString(),
        devices: [
          {
            deviceId: 'device_456',
            deviceName: 'Jane\'s Windows PC',
            active: true,
            lastSeen: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
            registeredAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString()
          },
          {
            deviceId: 'device_789',
            deviceName: 'Team Laptop',
            active: false,
            lastSeen: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(),
            registeredAt: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString()
          }
        ],
        usage: {
          totalSessions: 45,
          totalConversations: 280,
          totalMessages: 1400,
          lastUsed: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString()
        }
      },
      {
        userId: 'demo_user_3',
        userName: 'Tech Corp',
        userEmail: 'admin@techcorp.com',
        tier: 'BUSINESS',
        status: 'active',
        createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
        devices: [
          {
            deviceId: 'device_101',
            deviceName: 'Server-01',
            active: true,
            lastSeen: new Date().toISOString(),
            registeredAt: new Date(Date.now() - 25 * 24 * 60 * 60 * 1000).toISOString()
          },
          {
            deviceId: 'device_102',
            deviceName: 'Dev-Machine-01',
            active: true,
            lastSeen: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
            registeredAt: new Date(Date.now() - 20 * 24 * 60 * 60 * 1000).toISOString()
          }
        ],
        usage: {
          totalSessions: 120,
          totalConversations: 850,
          totalMessages: 4250,
          lastUsed: new Date().toISOString()
        }
      }
    ];
  }

  getDemoAnalytics() {
    return {
      totalUsers: 3,
      totalConversations: 1280,
      totalMessages: 6400,
      averageSuccessRate: 0.94,
      dailyStats: {
        '2024-01-15': { users: 2, conversations: 45, messages: 225 },
        '2024-01-16': { users: 3, conversations: 67, messages: 335 },
        '2024-01-17': { users: 3, conversations: 89, messages: 445 }
      }
    };
  }

  getDemoStats() {
    return {
      totalUsers: 3,
      activeDevices: 4,
      totalRevenue: 80, // $5 + $25 + $50
      aiInteractions: 6400
    };
  }

  getDemoLicenses() {
    // Combine static demo licenses with PayPal-generated ones
    const staticDemoLicenses = [
      {
        licenseId: 'ZAI-DEMO001',
        userName: 'John Doe',
        userEmail: 'john@example.com',
        tier: 'PERSONAL',
        tierConfig: { name: 'Personal', maxDevices: 1, price: 5 },
        status: 'active',
        createdAt: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(),
        expiresAt: null, // Lifetime
        devices: [
          {
            deviceId: 'device_123',
            deviceName: 'John\'s MacBook Pro',
            active: true,
            lastSeen: new Date().toISOString(),
            registeredAt: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString()
          }
        ],
        token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.demo_token_personal'
      },
      {
        licenseId: 'ZAI-DEMO002',
        userName: 'Jane Smith',
        userEmail: 'jane@company.com',
        tier: 'SMALL_TEAM',
        tierConfig: { name: 'Small Team', maxDevices: 10, price: 25 },
        status: 'active',
        createdAt: new Date(Date.now() - 14 * 24 * 60 * 60 * 1000).toISOString(),
        expiresAt: null, // Lifetime
        devices: [
          {
            deviceId: 'device_456',
            deviceName: 'Jane\'s Windows PC',
            active: true,
            lastSeen: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
            registeredAt: new Date(Date.now() - 10 * 24 * 60 * 60 * 1000).toISOString()
          },
          {
            deviceId: 'device_789',
            deviceName: 'Team Laptop',
            active: false,
            lastSeen: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(),
            registeredAt: new Date(Date.now() - 8 * 24 * 60 * 60 * 1000).toISOString()
          }
        ],
        token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.demo_token_small_team'
      },
      {
        licenseId: 'ZAI-DEMO003',
        userName: 'Tech Corp',
        userEmail: 'admin@techcorp.com',
        tier: 'BUSINESS',
        tierConfig: { name: 'Business', maxDevices: 500, price: 50 },
        status: 'active',
        createdAt: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
        expiresAt: null, // Lifetime
        devices: [
          {
            deviceId: 'device_101',
            deviceName: 'Server-01',
            active: true,
            lastSeen: new Date().toISOString(),
            registeredAt: new Date(Date.now() - 25 * 24 * 60 * 60 * 1000).toISOString()
          },
          {
            deviceId: 'device_102',
            deviceName: 'Dev-Machine-01',
            active: true,
            lastSeen: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
            registeredAt: new Date(Date.now() - 20 * 24 * 60 * 60 * 1000).toISOString()
          }
        ],
        token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.demo_token_business'
      }
    ];

    // Return combined static and PayPal-generated licenses
    return [...staticDemoLicenses, ...this.demoLicenses];
  }

  async getSystemStats() {
    // Return demo stats when in demo mode
    if (this.demoMode) {
      return this.getDemoStats();
    }
    // Implementation for real stats
    return {
      totalUsers: 0,
      activeDevices: 0,
      totalRevenue: 0,
      aiInteractions: 0
    };
  }
}
