<?php

declare(strict_types=1);


namespace App\Blog\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\File;

class MarketplaceClient
{
    /**
     * 拉取市场包列表。
     *
     * @return array<int, array<string, mixed>>
     */
    public function items(): array
    {
        $url = config('market.url');

        if (! $url) {
            return [];
        }

        $response = Http::timeout(config('market.timeout', 15))
            ->withToken(config('market.token', ''))
            ->get(rtrim($url, '/').'/items');

        $response->throw();

        $items = $response->json('items', []);

        // 规范化市场契约：price 分、type（plugin/theme）、name
        return array_map(function (array $item) {
            $item['price'] = (int) ($item['price'] ?? 0);
            $item['type'] = $item['type'] ?? 'plugin';
            $item['name'] = $item['name'] ?? null;

            return $item;
        }, is_array($items) ? $items : []);
    }

    public function download(string $url): string
    {
        $response = Http::timeout(60)->get($url);
        $response->throw();

        $tmp = storage_path('app/tmp/market-'.basename(parse_url($url, PHP_URL_PATH)));
        File::ensureDirectoryExists(dirname($tmp));
        File::put($tmp, $response->body());

        return $tmp;
    }
}
