<?php

namespace Tests\Services\CommodityBarcodeService;

use App\Commodity;
use App\CommodityBarcode;
use App\Services\CacheService;
use App\Services\CommodityBarcodeService;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\Cache;
use Tests\TestCase;

class InsertMany_onCommoditiesTest extends TestCase
{

    /** @var CommodityBarcodeService $service */
    public $service;
    public $data=[];
    public function setUp(): void
    {
        parent::setUp();
        $this->service = app('CommodityBarcodeService');
        ($this->data['commodity']=(new Commodity()))->save();
        $this->data['barcodes']=['A1','B1','C2'];
        $this->data['commodityBarcodes']=new Collection();
    }

    public function testInsert(){
        $inputs=[
            'commodity_id'=>$this->data['commodity']['id'],
            'barcodes'=>$this->data['barcodes']
        ];
        $this->service->insertMany_onCommodities([$inputs]);
        $this->data['commodityBarcodes']=CommodityBarcode::query()
            ->where('commodity_id',$this->data['commodity']['id'])
            ->whereIn('code',$this->data['barcodes'])
            ->get();
        $resultArr=$this->data['commodityBarcodes']->map(function ($commodityBarcode){
            return [$commodityBarcode['commodity_id'],$commodityBarcode['code']];
        });
        $expectArr = (function () {
            $arr=[];
            foreach ($this->data['barcodes'] as $barcode) {
                $arr[]=[
                    $this->data['commodity']['id'],$barcode
                ];
            }
            return $arr;
        })();
        $this->assertEquals(json_encode($expectArr),json_encode($resultArr));

        $result=$this->service->insertMany_onCommodities([]);
        $this->assertEquals(false,$result);
    }


    public function tearDown(): void
    {
        $this->data['commodity']->delete();
        CommodityBarcode::destroy($this->data['commodityBarcodes']->map(function ($commodityBarcode){
            return $commodityBarcode['id'];
        }));
        parent::tearDown();
    }
}
