<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class AwsApiService
{
    protected $baseUrl;
    protected $masterKey;

    public function __construct()
    {
        $this->baseUrl = config('services.aws_car_advisor.url');
        $this->masterKey = config('services.aws_car_advisor.key');
    }

    public function proxyRequest(string $endpoint, string $method, array $data = [])
    {
        $url = rtrim($this->baseUrl, '/') . '/' . ltrim($endpoint, '/');

        $start = microtime(true);

        try {
            $response = Http::withHeaders([
                'x-api-key' => $this->masterKey,
                'Content-Type' => 'application/json',
            ])
            ->{$method == 'GET' ? 'get' : 'post'}($url, $data);

            $duration = (microtime(true) - $start) * 1000;

            return [
                'success' => $response->successful(),
                'status' => $response->status(),
                'body' => $response->json(),
                'duration_ms' => round($duration, 2)
            ];
        } catch (\Exception $e) {
            Log::error('AWS API Proxy Error: ' . $e->getMessage());
            return [
                'success' => false,
                'status' => 502,
                'body' => ['error' => 'Backend service unavailable'],
                'duration_ms' => 0
            ];
        }
    }


    public function call($endpoint, $method = 'GET', $data = [])
    {
        $response = Http::withHeaders([
            'x-api-key' => config('services.aws.api_key'),
        ])->{$method === 'GET' ? 'get' : 'post'}(
            rtrim(config('services.aws.url'), '/') . '/' . ltrim($endpoint, '/'),
            $data
        );

        return $response;
    }
}