<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

/**
 * 健康检查控制器
 * 用于检查依赖服务状态
 */
class HealthCheckController extends Controller
{
    /**
     * 检查所有依赖服务状态
     */
    public function index(): JsonResponse
    {
        $checks = [
            'question_bank_api' => $this->checkQuestionBankService(),
            'learning_analytics' => $this->checkLearningAnalyticsService(),
            'database' => $this->checkDatabase(),
        ];

        $allHealthy = collect($checks)->every(fn($check) => $check['status'] === 'healthy');

        return response()->json([
            'success' => true,
            'overall_status' => $allHealthy ? 'healthy' : 'unhealthy',
            'checks' => $checks,
            'timestamp' => now()->toISOString(),
        ]);
    }

    /**
     * 检查题库服务
     */
    private function checkQuestionBankService(): array
    {
        try {
            $baseUrl = config('services.question_bank.base_url', 'http://localhost:5015');
            $response = Http::timeout(5)->get($baseUrl . '/health');

            return [
                'status' => $response->successful() ? 'healthy' : 'unhealthy',
                'message' => $response->body(),
                'response_time' => $response->transferStats ? $response->transferStats->getTotalTime() : null,
            ];
        } catch (\Exception $e) {
            Log::error('题库服务健康检查失败', ['error' => $e->getMessage()]);

            return [
                'status' => 'unhealthy',
                'message' => $e->getMessage(),
                'error_code' => $e->getCode(),
            ];
        }
    }

    /**
     * 检查学习分析服务
     */
    private function checkLearningAnalyticsService(): array
    {
        try {
            $baseUrl = config('services.learning_analytics.base_url', 'http://localhost:5016');
            $response = Http::timeout(5)->get($baseUrl . '/health');

            return [
                'status' => $response->successful() ? 'healthy' : 'unhealthy',
                'message' => $response->body(),
                'response_time' => $response->transferStats ? $response->transferStats->getTotalTime() : null,
            ];
        } catch (\Exception $e) {
            Log::error('学习分析服务健康检查失败', ['error' => $e->getMessage()]);

            return [
                'status' => 'unhealthy',
                'message' => $e->getMessage(),
                'error_code' => $e->getCode(),
            ];
        }
    }

    /**
     * 检查数据库连接
     */
    private function checkDatabase(): array
    {
        try {
            // 检查 MySQL 主库
            $mysqlResult = \DB::connection('mysql')->select('SELECT 1 as test');

            // 检查题库 PostgreSQL（如果存在）
            $pgResult = null;
            try {
                $pgResult = \DB::connection('pgsql')->select('SELECT 1 as test');
            } catch (\Exception $e) {
                // PostgreSQL 连接失败但不影响主流程
            }

            return [
                'status' => 'healthy',
                'message' => 'MySQL连接正常',
                'mysql' => 'healthy',
                'postgresql' => $pgResult ? 'healthy' : 'not_configured',
            ];
        } catch (\Exception $e) {
            Log::error('数据库健康检查失败', ['error' => $e->getMessage()]);

            return [
                'status' => 'unhealthy',
                'message' => $e->getMessage(),
                'error_code' => $e->getCode(),
            ];
        }
    }
}
