<?php


namespace Tests\AsnSync\Services;


use App\OracleDOCASNHeader;
use App\Services\StoreService;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class SyncWmsAsnDataTest extends TestCase
{
    /** @var StoreService $service */
    public $service;
    public $asnHeaders;
    public $asnHeadersEdit;
    public $asnHeadersTotal;
    public $startDate;
    public $stores;
    public function setUp(): void
    {

        parent::setUp(); // TODO: Change the autogenerated stub
        $this->startDate = \Illuminate\Support\Carbon::now()->subSeconds(300);
        $this->service = app(StoreService::class);
        $this->asnHeaders = OracleDOCASNHeader::query()
            ->with(['asnType', 'asnStatus', 'asnDetails' => function ($query) {
                $query->with(['lineStatus', 'qualityStatus', 'basSku']);
            }])
            ->where('addTime', '>=', $this->startDate)
            ->get();
        $this->asnHeadersEdit = OracleDOCASNHeader::query()
            ->with(['asnType', 'asnStatus', 'asnDetails' => function ($query) {
                $query->with(['lineStatus', 'qualityStatus', 'basSku']);
            }])
            ->where('EditTime', '>=', $this->startDate)
            ->whereColumn('EditTime', '<>', 'addTime')
            ->get();
    }


    public function testSyncWmsAsnData()
    {
          if (!$this->asnHeaders && !$this->asnHeadersEdit) return null;
        if (!empty($this->asnHeadersEdit)){
            foreach ($this->asnHeadersEdit as $asnHerder)
                $this->asnHeaders->add($asnHerder);
        }
        if ($this->asnHeaders) {
            $this->service->syncWmsAsnData($this->startDate);
            $this->stores = $this->service->getByWms($this->asnHeaders);
            $this->assertNotEmpty($this->stores);
        } else {
            $this->assertNull($this->asnHeaders);
        }
    }

    public function tearDown(): void
    {
        $storeIds = [];
        foreach ($this->stores as $store) {
            array_push($storeIds, $store->id);
        }
        DB::table('stores')->whereIn('asn_code', data_get($this->asnHeaders, '*.asnno'))->delete();
        DB::table('store_items')->whereIn('store_id', $storeIds)->delete();
        parent::tearDown(); // TODO: Change the autogenerated stub
    }
}
