<?php

namespace Tests\Services\CacheService\GetOrExecuteTest;

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'];
        $inserts=(function(){
            $targets=[];
            foreach ($this->data['barcodes'] as $barcode) {
                $targets[]=['commodity_id'=>$this->data['commodity']['id'],'code'=>$barcode];
            }
            return $targets;
        })();
        CommodityBarcode::query()->insert($inserts);
        $this->data['commodityBarcodes']=CommodityBarcode::query()
            ->where('commodity_id',$this->data['commodity']['id'])
            ->whereIn('code',$this->data['barcodes'])
            ->get();
    }

    public function testDeleted(){
        $this->assertGreaterThan(0,$this->data['commodityBarcodes']->count());
        $destroyIds = $this->data['commodityBarcodes']->map(function ($commodityBarcode) {
            return $commodityBarcode['id'];
        });
        $commodityBarcodes = CommodityBarcode::query()->whereIn('id', $destroyIds)->get();
        $this->service->destroyCollections($commodityBarcodes);

        $commodityBarcodesResult = CommodityBarcode::query()->whereIn('id', $destroyIds)->get();
        $this->assertEquals(0, $commodityBarcodesResult->count());
    }


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