<?php

namespace Tests\Services\LogisticService;

use App\Logistic;
use App\OracleBasCustomer;
use App\Services\LogisticService;
use App\Services\OracleBasCustomerService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class GetLogisticByCodesTest extends TestCase
{
    /** @var LogisticService $service */
    private $service;
    private $data;

    public function setUp(): void
    {
        parent::setUp(); // TODO: Change the autogenerated stub
        $this->service  = app('LogisticService');
        $logistic1 =  factory(Logistic::class)->create();
        $logistic2 =  factory(Logistic::class)->create();
        $OracleBasCustomer1 = factory(OracleBasCustomer::class)->make(['customer_type' => 'CA','customerid'=>$logistic1->code,'descr_c' =>$logistic1->name ]);
        $OracleBasCustomer2 = factory(OracleBasCustomer::class)->make(['customer_type' => 'CA','customerid'=>$logistic2->code,'descr_c' =>$logistic2->name ]);
        $OracleBasCustomers = collect([$OracleBasCustomer1,$OracleBasCustomer2]);
        $this->data['baseCustomers'] = $OracleBasCustomers;
        $this->mock(OracleBasCustomerService::class,function ($mock)use($OracleBasCustomer1,$OracleBasCustomer2){
            $mock->shouldReceive('first')->with(["Customer_Type"=>'CA',"CustomerID"=>$OracleBasCustomer1['customerid']])->andReturn($OracleBasCustomer1);
            $mock->shouldReceive('first')->with(["Customer_Type"=>'CA',"CustomerID"=>$OracleBasCustomer2['customerid']])->andReturn($OracleBasCustomer2);
        });

        $this->data['baseCustomers'] = $OracleBasCustomers;
        $this->data['logistics'] = collect([$logistic1,$logistic2]);
    }

    /**
     * @test
     */
    public function getLogisticByCodes()
    {
        $logistics = $this->service->getLogisticByCodes(data_get($this->data['logistics'],'*.code'));
        $this->assertNotEmpty($logistics);
        foreach ($logistics as $logistic) {
            $baseCustomer = $this->data['baseCustomers']->where('customerid',$logistic->code)->where('descr_c',$logistic->name);
            $this->assertNotEmpty($baseCustomer);
            $this->assertEquals(1,$baseCustomer->count());
        }
        foreach ($this->data['baseCustomers'] as $baseCustomer) {
            $logistic = $logistics->where('code',$baseCustomer['customerid'])->where('name',$baseCustomer['descr_c']);
            $this->assertNotEmpty($logistic);
            $this->assertEquals(1,$logistic->count());
        }
    }

    public function tearDown(): void
    {
        foreach ($this->data['baseCustomers'] as $baseCustomer) {
            cache()->forget('getLogisticByCode_'.$baseCustomer['customerid']);
        }
        foreach ( $this->data['logistics'] as $item) {
            $item->delete();
        }
        parent::tearDown(); // TODO: Change the autogenerated stub
    }
}
