<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

use App\Models\Stock\Good;
use App\Models\Stock\Purchase;

class GoodTest extends TestCase
{
    use DatabaseTransactions;

    public function testSimpleAveragePriceCalculation()
    {
        $purchase = factory(Purchase::class)->make();
        $purchase->quantity = 10;
        $purchase->unit_price = 10;
        $purchase->save();

        Good::updateAverageUnitPrice($purchase->good->id);

        $good = Good::findOrFail($purchase->good->id);

        $this->assertTrue(10 == $good->average_unit_price);
    }

    public function testAveragePriceCalculation()
    {
        $good = factory(Good::class)->create();

        $m1 = factory(Purchase::class)->make();
        $m1->quantity = 100;
        $m1->unit_price = 5;
        $m1->good()->associate($good);
        $m1->save();

        $m2 = factory(Purchase::class)->make();
        $m2->quantity = 100;
        $m2->unit_price = 7;
        $m2->good()->associate($good);        
        $m2->save();

        Good::updateAverageUnitPrice($good->id);

        $good = Good::findOrFail($good->id);

        $this->assertTrue(6 == $good->average_unit_price);
    }

    public function testAveragePriceCalculationOnlyUsesMovementsFromLast30Days()
    {
        $good = factory(Good::class)->create();

        $m1 = factory(Purchase::class)->make();
        $m1->quantity = 100;
        $m1->unit_price = 9;
        $m1->good()->associate($good);
        $m1->purchased_at = \Carbon\Carbon::now()->subDays(31);
        $m1->save();

        $m2 = factory(Purchase::class)->make();
        $m2->quantity = 100;
        $m2->unit_price = 6;
        $m2->good()->associate($good);
        $m2->purchased_at = \Carbon\Carbon::now()->subDays(30);
        $m2->save();

        $m3 = factory(Purchase::class)->make();
        $m3->quantity = 100;
        $m3->unit_price = 8;
        $m3->good()->associate($good);
        $m3->purchased_at = \Carbon\Carbon::now();
        $m3->save();

        $m4 = factory(Purchase::class)->make();
        $m4->quantity = 100;
        $m4->unit_price = 9;
        $m4->good()->associate($good);
        $m4->purchased_at = \Carbon\Carbon::now()->addDays(1);
        $m4->save();

        Good::updateAverageUnitPrice($good->id);

        $good = Good::findOrFail($good->id);

        $this->assertEquals(7, $good->average_unit_price);
    }
}
