<?php

namespace App\Http\Controllers\api\v1;

use App\Http\Controllers\BaseController;
use App\Services\ExternalApiSafetyService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;

class ExternalApiStatusController extends BaseController
{
    /**
     * Get external API safety status
     */
    public function getStatus()
    {
        $status = ExternalApiSafetyService::getSafetyStatus();
        
        return Response::json([
            'success' => true,
            'status' => $status,
            'timestamp' => now()->toISOString()
        ]);
    }

    /**
     * Test external API connectivity (dry run)
     */
    public function testConnectivity(Request $request)
    {
        $service = $request->get('service', 'all');
        
        $result = ExternalApiSafetyService::dryRun($service, function() {
            return 'Test function';
        }, [
            'test_data' => 'This would be synced in production',
            'timestamp' => now()->toISOString()
        ]);
        
        return Response::json($result);
    }

    /**
     * Get integration warnings for dashboard
     */
    public function getWarnings()
    {
        $status = ExternalApiSafetyService::getSafetyStatus();
        
        return Response::json([
            'success' => true,
            'warnings' => $status['warnings'],
            'has_warnings' => count($status['warnings']) > 0,
            'environment' => $status['environment'],
            'safe_to_sync' => $status['safe_to_sync']
        ]);
    }

    /**
     * Update external API settings (for admin use)
     */
    public function updateSettings(Request $request)
    {
        // Only allow in development environments for safety
        if (!ExternalApiSafetyService::isDevelopmentEnvironment()) {
            return Response::json([
                'success' => false,
                'message' => 'API settings can only be changed in development environments'
            ], 403);
        }

        $settings = $request->validate([
            'disable_external_apis' => 'boolean',
            'xero_sync_enabled' => 'boolean', 
            'xero_sync_enabled' => 'boolean'
        ]);

        // Note: In a real implementation, you'd update environment variables or database settings
        // For now, just return what the settings would be
        return Response::json([
            'success' => true,
            'message' => 'Settings would be updated (demo only)',
            'requested_settings' => $settings,
            'note' => 'In production, these would update .env file or database settings'
        ]);
    }
} 