<?php

namespace App\Http\Controllers\Api\V1\Admin;

use App\Http\Controllers\Controller;
use App\Models\NotificationLog;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class SystemMetricsController extends Controller
{
    use ApiResponse;

    public function __invoke(Request $request)
    {
        $organizationId = $request->user()->organization_id;

        $databaseOk = true;
        try {
            DB::select('select 1');
        } catch (\Throwable) {
            $databaseOk = false;
        }

        $failedJobs = Schema::hasTable('failed_jobs') ? DB::table('failed_jobs')->count() : 0;
        $pendingJobs = Schema::hasTable('jobs') ? DB::table('jobs')->count() : 0;

        $notificationFailures24h = NotificationLog::query()
            ->where('organization_id', $organizationId)
            ->where('status', 'failed')
            ->where('updated_at', '>=', now()->subDay())
            ->count();

        return $this->success([
            'database' => [
                'healthy' => $databaseOk,
                'driver' => DB::connection()->getDriverName(),
            ],
            'queue' => [
                'pending_jobs' => $pendingJobs,
                'failed_jobs' => $failedJobs,
            ],
            'notifications' => [
                'failed_last_24_hours' => $notificationFailures24h,
            ],
            'runtime' => [
                'app_env' => app()->environment(),
                'debug' => (bool) config('app.debug'),
                'queue_connection' => config('queue.default'),
                'cache_store' => config('cache.default'),
                'timestamp' => now()->toIso8601String(),
            ],
        ]);
    }
}
