]<?php

use App\Rack;
use App\Warehouse;

class WarehouseTest extends TestCase
{
    public function test_it_adds_a_rack()
    {
        $warehouse = $this->createWarehouse();
        $warehouse->addRack($this->makeRack());
        $warehouse->addRack($this->makeRack());
        $warehouse->addRack($this->makeRack());
        $this->assertEquals(3, $warehouse->racks()->count());
    }

    public function test_adds_multiple_racks()
    {
        $warehouse = $this->createWarehouse();
        $warehouse->addRacks($this->makeRack(5));
        $this->assertEquals(5, $warehouse->racks()->count());
    }

    public function test_removes_only_the_racks_not_in_given_ids()
    {
        $warehouse = $this->createWarehouse();
        $racks     = $this->makeRack(10);
        $warehouse->addRacks($racks);
        $chunks        = $racks->chunk(5);
        $retain        = array_pluck($chunks->first(), 'id');
        $mustBeDeleted = array_pluck($chunks->last(), 'id');
        $warehouse->removeRacksNotIn($retain);
        $this->assertEquals(0, $warehouse->racks()->whereIn('id', $mustBeDeleted)->count());
        $this->assertEquals(5, $warehouse->racks()->whereIn('id', $retain)->count());
    }

    public function test_it_should_add_a_new_rack()
    {
        $warehouse = $this->createWarehouse();
        $rack      = $this->makeRack()->toArray();
        $warehouse->addOrUpdateRack($rack);
        $this->assertEquals(1, $warehouse->racks()->count());
    }

    public function test_it_should_update_the_existing_rack()
    {
        $warehouse = $this->createWarehouse();
        $rack      = $warehouse->racks()->save($this->makeRack());
        $this->assertEquals(1, $warehouse->racks()->count());
        $rack->name = 'New Name';
        $warehouse->addOrUpdateRack($rack->toArray());
        $this->assertEquals(1, $warehouse->racks()->count());
        $this->assertEquals(1, $warehouse->racks()->whereName('New Name')->count());
    }

    private function createWarehouse($attributes = [])
    {
        return factory(Warehouse::class)->create($attributes);
    }

    private function makeRack($count = 1, $attributes = [])
    {
        return factory(Rack::class, $count)->make($attributes + ['make_id' => factory(App\Make::class)->create()->id]);
    }
}
