<?php

namespace App\Platform\Tools\Request;

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

class CompanyRequest extends HttpClient
{

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

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

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

        return $stores->first();


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

        return $collection;
    }

   

    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/companies/$id";
        return static::put($path, [], $data);
    }




}
