<?php

namespace App\Platform\Tools\Request;

use App\Platform\Tools\HttpClient;
use Hyperf\Collection\LazyCollection;

class StoreRequest extends HttpClient
{

    public static function one(string $id): array
    {
        return parent::get("api/ext/stores/$id");
    }
    
    public static function find(string $name, string $platform)
    {

        $stores = self::all();
        $stores = $stores->filter(function($el) use ($name, $platform){
            return $el['platform']['name'] == $platform &&  strtolower($el['label']) == $name ? $el : null;
        });

        if($stores->isEmpty()){
            throw new \InvalidArgumentException("tools 中未找到平台为 $platform, name 为 $name 的店铺信息，请确认 tools 系统中已创建该平台和店铺的记录！");
        }

        return $stores->first();


    }
    public static function all(int $page = 1, int $size = 500, $query = []): LazyCollection
    {
        $path = 'api/ext/stores';
        $collection = new LazyCollection();
        static::fetch($collection, $path, $page, $size, $query);
        if($collection->isEmpty()){
            throw new \InvalidArgumentException("获取的远程 tools 商店列表为空，请检查 token 配置");
        }
        return $collection;
    }

    public static function orderNone(array $query) {
        $path = 'api/ext/stores/order-none';
        return static::get($path, $query);

    }

    protected static function fetch(LazyCollection  &$collection, $path, $page, $size, $query)
    {
        $init_query = [
            'page' => $page,
            'size' => $size
        ];

        $query =  !empty($query) ? array_merge($init_query, $query) : $init_query;

        $response = static::get($path, $query);

        if($response['data']){
            $collection = $collection->merge($response['data']);
        }

        if($response['page'] <  $response['total_page']){
            self::fetch($collection, $path, $page + 1, $size, $query);
        }
    }

    public static function update(int $id, array $data): array
    {
        $path = "/api/ext/stores/$id";
        return static::put($path, [], $data);
    }




}
