<?php

namespace App\Http\Controllers;

use App\Models\ApiRequestLog;
use Illuminate\Http\JsonResponse;
use Inertia\Inertia;
use Inertia\Response;

class ApiLogController extends Controller
{
    public function index(): Response
    {
        $search = request()->string('search')->toString();
        $status = request()->string('status')->toString();

        $logs = ApiRequestLog::query()
            ->search($search)
            ->byStatus($status)
            ->orderByDesc('created_at')
            ->paginate(25)
            ->withQueryString()
            ->through(fn (ApiRequestLog $log) => [
                'id' => $log->id,
                'created_at' => $log->created_at?->toJSON(),
                'method' => $log->method,
                'endpoint' => $log->endpoint,
                'status' => $log->status,
                'duration_ms' => $log->duration_ms,
                'error_message' => $log->error_message,
                'request_context' => $log->request_context,
                'response_summary' => $log->response_summary,
            ]);

        return Inertia::render('ApiLogs/Index', [
            'logs' => $logs,
            'filters' => [
                'search' => $search,
                'status' => $status,
            ],
        ]);
    }

    public function responseBody(ApiRequestLog $log): JsonResponse
    {
        return response()->json([
            'response_body' => $log->response_body,
            'request_context' => $log->request_context,
        ]);
    }
}
