<?php

namespace Modules\ProductCompat\Entities\Enrichment\Providers;

use App\Product;
use Illuminate\Support\Facades\Http;
use Modules\ProductCompat\Entities\Enrichment\EnrichmentProvider;
use Modules\ProductCompat\Entities\Enrichment\EnrichmentResult;

/**
 * Commercial parts/compatibility API. The cleanest, ToS-safe source. Configure
 * `PRODUCTCOMPAT_API_URL` and `PRODUCTCOMPAT_API_KEY` (see config). The endpoint
 * is expected to accept a `q` query and return JSON containing `part_numbers`
 * and/or `compatible_models` / `device_models` arrays — parsed defensively.
 */
class PaidApiProvider implements EnrichmentProvider
{
    public function key(): string
    {
        return 'api';
    }

    public function isAvailable(): bool
    {
        $cfg = config('productcompat.enrichment.paid_api', []);

        return ! empty($cfg['base_url']) && ! empty($cfg['key']);
    }

    public function fetch(Product $product): EnrichmentResult
    {
        $cfg = config('productcompat.enrichment.paid_api', []);
        $timeout = (int) config('productcompat.enrichment.timeout', 15);

        $query = trim(implode(' ', array_filter([
            optional($product->brand)->name,
            $product->name,
        ])));

        try {
            $resp = Http::timeout($timeout)
                ->withToken($cfg['key'])
                ->acceptJson()
                ->get($cfg['base_url'], ['q' => $query, 'sku' => $product->sku]);

            if ($resp->failed()) {
                return EnrichmentResult::fail('API HTTP ' . $resp->status(), $resp->body());
            }

            $json = $resp->json() ?? [];
            $candidates = $this->mapResponse($json);

            return new EnrichmentResult(true, $candidates, $json);
        } catch (\Throwable $e) {
            return EnrichmentResult::fail($e->getMessage());
        }
    }

    /**
     * Map a flexible JSON shape into our candidate structure.
     */
    protected function mapResponse(array $json): array
    {
        $conf = (int) (config('productcompat.enrichment.confidence.api') ?? 80);

        $parts = [];
        foreach ((array) ($json['part_numbers'] ?? $json['parts'] ?? []) as $p) {
            $value = is_array($p) ? ($p['value'] ?? $p['part_number'] ?? null) : $p;
            if (! $value) {
                continue;
            }
            $parts[] = [
                'value'      => (string) $value,
                'type'       => is_array($p) ? ($p['type'] ?? 'mpn') : 'mpn',
                'confidence' => $conf,
            ];
        }

        $devices = [];
        foreach ((array) ($json['device_models'] ?? $json['compatible_models'] ?? $json['models'] ?? []) as $d) {
            if (is_array($d)) {
                $devices[] = [
                    'brand'      => $d['brand'] ?? null,
                    'series'     => $d['series'] ?? null,
                    'model'      => $d['model'] ?? ($d['name'] ?? ''),
                    'confidence' => $conf,
                ];
            } else {
                $devices[] = ['brand' => null, 'series' => null, 'model' => (string) $d, 'confidence' => $conf];
            }
        }

        return ['part_numbers' => $parts, 'device_models' => $devices];
    }
}
