<?php

namespace App\Services;

use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;

class ExternalApiSafetyService
{
    /**
     * Check if external API operations are safe to perform
     */
    public static function isSafeToSync(string $service = 'all'): bool
    {
        // Allow Xero sync in development for testing
        if ($service === 'xero') {
            return self::isServiceEnabled($service);
        }

        // Check environment - prevent auto-sync in development
        if (self::isDevelopmentEnvironment()) {
            Log::warning("External API sync blocked - development environment detected", [
                'service' => $service,
                'environment' => app()->environment()
            ]);
            return false;
        }

        // Check if external APIs are globally enabled
        if (!self::isExternalApiEnabled()) {
            Log::info("External API sync blocked - globally disabled", [
                'service' => $service
            ]);
            return false;
        }

        // Check service-specific settings
        if (!self::isServiceEnabled($service)) {
            Log::info("External API sync blocked - service disabled", [
                'service' => $service
            ]);
            return false;
        }

        return true;
    }

    /**
     * Check if we're in a development environment
     */
    public static function isDevelopmentEnvironment(): bool
    {
        return in_array(app()->environment(), ['local', 'development', 'testing']);
    }

    /**
     * Check if external APIs are globally enabled
     */
    public static function isExternalApiEnabled(): bool
    {
        try {
            // Check if there's a global setting to disable external APIs
            return !env('DISABLE_EXTERNAL_APIS', false);
        } catch (\Exception $e) {
            // If we can't check settings, be safe and disable
            return false;
        }
    }

    /**
     * Check if a specific service is enabled
     */
    public static function isServiceEnabled(string $service): bool
    {
        // Check service-specific settings from Admin Integration Settings
        $enabledServices = [
            'xero' => env('XERO_SYNC_ENABLED', true) && \App\Models\Setting::get('integrations.xero.enabled', false),
            'all' => true
        ];

        return $enabledServices[$service] ?? true;
    }

    /**
     * Get a safe response when sync is blocked
     */
    public static function getSafeResponse(string $service, string $action = 'sync'): array
    {
        $message = "External API {$action} is currently disabled";
        
        if (self::isDevelopmentEnvironment()) {
            $message .= " (development environment)";
        }

        return [
            'success' => false,
            'blocked' => true,
            'message' => $message,
            'service' => $service,
            'environment' => app()->environment(),
            'help' => 'To enable external API sync, set DISABLE_EXTERNAL_APIS=false in your .env file and ensure the service is enabled in Admin Integration Settings.'
        ];
    }

    /**
     * Log a sync attempt with safety information
     */
    public static function logSyncAttempt(string $service, array $data = [], bool $dryRun = false): void
    {
        Log::info("External API sync attempt", [
            'service' => $service,
            'environment' => app()->environment(),
            'safe_to_sync' => self::isSafeToSync($service),
            'dry_run' => $dryRun,
            'data_preview' => array_slice($data, 0, 3), // Only log first 3 items for privacy
            'data_count' => count($data)
        ]);
    }

    /**
     * Perform a dry run - show what would be synced without actually doing it
     */
    public static function dryRun(string $service, callable $syncFunction, array $data = []): array
    {
        self::logSyncAttempt($service, $data, true);

        return [
            'success' => true,
            'dry_run' => true,
            'service' => $service,
            'message' => 'Dry run completed - no actual sync performed',
            'would_sync_count' => count($data),
            'environment' => app()->environment(),
            'preview' => array_slice($data, 0, 5) // Show first 5 items that would be synced
        ];
    }

    /**
     * Get environment safety status for dashboard
     */
    public static function getSafetyStatus(): array
    {
        return [
            'environment' => app()->environment(),
            'is_development' => self::isDevelopmentEnvironment(),
            'external_apis_enabled' => self::isExternalApiEnabled(),
            'services' => [
                'xero' => self::isServiceEnabled('xero')
            ],
            'safe_to_sync' => self::isSafeToSync(),
            'warnings' => self::getWarnings()
        ];
    }

    /**
     * Get safety warnings for display
     */
    private static function getWarnings(): array
    {
        $warnings = [];

        if (self::isDevelopmentEnvironment()) {
            $warnings[] = 'Running in development environment - external API sync is disabled for safety';
        }

        if (!self::isExternalApiEnabled()) {
            $warnings[] = 'External APIs are globally disabled via DISABLE_EXTERNAL_APIS setting';
        }

        if (!self::isServiceEnabled('xero')) {
            $warnings[] = 'Xero sync is disabled - check Admin Integration Settings';
        }

        return $warnings;
    }
} 