<?php

namespace App\Modules\Bookings;

use App\Modules\Stock\StockTransaction;
use App\Modules\Stock\Stock;
use Exception;
use Illuminate\Support\Facades\Event;

class BuildCompleted
{
    /**
     * The build that was updated.
     *
     * @var \App\Modules\Bookings\Build
     */
    protected $build;

    /**
     * Subscribe to events.
     *
     * @param  mixed $events
     *
     * @return null
     */
    public function subscribe($events)
    {
        $events->listen('BuildCompleted', 'App\Modules\Bookings\BuildCompleted@fire');
    }

    /**
     * Fire the event.
     *
     * @param  \App\Modules\Bookings\Build $build
     *
     * @return bool
     */
    public function fire($build)
    {
        $this->build = $build;
        $this->createTransaction($build->stock, $build->quantity);
    }

    /**
     * Create a stock transaction that will
     * automatically update the stock.
     *
     * @return bool
     */
    protected function createTransaction(Stock $component, $quantity)
    {
        $transaction = StockTransaction::create([
            'stock_id'     => $component->id,
            'related_type' => $this->build->related_type,
            'related_id'   => $this->build->related_id,
            'quantity'     => $quantity,
        ]);

        if (! $transaction->exists) {
            throw new Exception('Failed to create stock transaction, '.json_encode($transaction->errors->all()));
        }

        return true;
    }
}
