<?php

namespace App\Services;

use App\Models\ApiLog;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Str;
use Throwable;

class ApiLogger
{
    /**
     * Execute an HTTP request and log it to api_logs.
     *
     * The callable must return an Illuminate\Http\Client\Response.
     * Exceptions are logged and re-thrown so the caller handles them.
     *
     * @param  callable(): Response  $request
     */
    public function send(string $service, string $method, string $url, callable $request): Response
    {
        $start = microtime(true);
        $statusCode = null;
        $error = null;

        try {
            $response = $request();
            $statusCode = $response->status();

            if ($response->failed()) {
                $error = Str::limit($response->body(), 1000);
            }

            return $response;
        } catch (Throwable $e) {
            $error = $e->getMessage();

            throw $e;
        } finally {
            ApiLog::create([
                'service' => $service,
                'method' => strtoupper($method),
                'url' => $url,
                'status_code' => $statusCode,
                'duration_ms' => (int) round((microtime(true) - $start) * 1000),
                'error' => $error,
            ]);
        }
    }
}
