/**
 * API Route: Check Tor status
 * GET /api/privacy/tor-status
 */

import type { NextApiRequest, NextApiResponse } from 'next';
import { getTorService } from '../../../lib/services/tor';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  if (req.method !== 'GET') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  try {
    const torService = getTorService();

    // Check if Tor is enabled in configuration
    const isEnabled = process.env.TOR_ENABLED === 'true';

    // Check if request came through Tor
    const isTorConnection = torService.isRequestFromTor(req.headers);

    let isAvailable = false;
    let circuitInfo = null;
    let onionAddress = null;

    if (isEnabled) {
      // Check if Tor daemon is available
      try {
        isAvailable = await torService.isAvailable();

        if (isAvailable) {
          circuitInfo = await torService.getCircuitInfo();
          onionAddress = torService.getOnionAddress();
        }
      } catch (error) {
        console.error('Error checking Tor availability:', error);
      }
    }

    res.status(200).json({
      success: true,
      tor: {
        enabled: isEnabled,
        available: isAvailable,
        connectionThroughTor: isTorConnection,
        onionAddress: onionAddress,
        circuit: circuitInfo,
      },
      privacy: {
        recommendTor: !isTorConnection,
        privacyLevel: isTorConnection ? 'high' : 'standard',
        ip: isTorConnection ? 'Hidden via Tor' : 'Visible',
      },
      recommendations: isTorConnection
        ? ['Your connection is private via Tor', 'Anonymous plant registration available']
        : [
            'For maximum privacy, access via Tor Browser',
            'Download Tor from https://www.torproject.org',
            `Or connect to our onion service: ${onionAddress || 'Not available'}`,
          ],
    });
  } catch (error: any) {
    console.error('Error checking Tor status:', error);
    res.status(500).json({ error: error.message || 'Internal server error' });
  }
}
