<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MonitoringService
{
    /**
     * Check database connectivity
     */
    public function checkDatabase(): array
    {
        try {
            $start = microtime(true);
            DB::connection()->getPdo();
            $duration = microtime(true) - $start;

            return [
                'status' => 'healthy',
                'response_time_ms' => round($duration * 1000, 2),
            ];
        } catch (\Exception $e) {
            return [
                'status' => 'unhealthy',
                'error' => $e->getMessage(),
            ];
        }
    }

    /**
     * Check cache connectivity
     */
    public function checkCache(): array
    {
        try {
            $start = microtime(true);
            $key = 'health_check_' . time();
            Cache::put($key, 'ok', 10);
            $value = Cache::get($key);
            Cache::forget($key);
            $duration = microtime(true) - $start;

            return [
                'status' => $value === 'ok' ? 'healthy' : 'unhealthy',
                'response_time_ms' => round($duration * 1000, 2),
            ];
        } catch (\Exception $e) {
            return [
                'status' => 'unhealthy',
                'error' => $e->getMessage(),
            ];
        }
    }

    /**
     * Get system metrics
     */
    public function getSystemMetrics(): array
    {
        return [
            'memory_usage' => $this->getMemoryUsage(),
            'disk_usage' => $this->getDiskUsage(),
            'database_size' => $this->getDatabaseSize(),
            'active_users' => $this->getActiveUsers(),
            'pending_orders' => $this->getPendingOrders(),
        ];
    }

    /**
     * Get memory usage
     */
    protected function getMemoryUsage(): array
    {
        $used = memory_get_usage(true);
        $peak = memory_get_peak_usage(true);
        $limit = ini_get('memory_limit');
        
        return [
            'used_mb' => round($used / 1024 / 1024, 2),
            'peak_mb' => round($peak / 1024 / 1024, 2),
            'limit' => $limit,
        ];
    }

    /**
     * Get disk usage
     */
    protected function getDiskUsage(): array
    {
        $total = disk_total_space(base_path());
        $free = disk_free_space(base_path());
        $used = $total - $free;

        return [
            'total_gb' => round($total / 1024 / 1024 / 1024, 2),
            'used_gb' => round($used / 1024 / 1024 / 1024, 2),
            'free_gb' => round($free / 1024 / 1024 / 1024, 2),
            'usage_percent' => round(($used / $total) * 100, 2),
        ];
    }

    /**
     * Get database size
     */
    protected function getDatabaseSize(): ?float
    {
        try {
            $databaseName = DB::connection()->getDatabaseName();
            $result = DB::select("
                SELECT 
                    ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS size_mb
                FROM information_schema.tables 
                WHERE table_schema = ?
            ", [$databaseName]);

            return $result[0]->size_mb ?? null;
        } catch (\Exception $e) {
            return null;
        }
    }

    /**
     * Get active users (last 24 hours)
     */
    protected function getActiveUsers(): int
    {
        try {
            return DB::table('sessions')
                ->where('last_activity', '>', now()->subDay()->timestamp)
                ->distinct('user_id')
                ->count('user_id');
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * Get pending orders count
     */
    protected function getPendingOrders(): int
    {
        try {
            return \App\Models\Order::where('status', 'awaiting_payment')->count();
        } catch (\Exception $e) {
            return 0;
        }
    }

    /**
     * Log performance metrics
     */
    public function logPerformanceMetrics(): void
    {
        $metrics = $this->getSystemMetrics();
        
        Log::info('System Performance Metrics', [
            'category' => 'monitoring',
            'metrics' => $metrics,
        ]);
    }
}

