<?php

namespace App\Console\Commands;

use App\Classes\Modules\Transactions\Processors\ApproveShippingInvoiceTransactionProcessor;
use App\Classes\ValueObjects\Constants\ApprovalStatus;
use App\Classes\ValueObjects\Constants\TransactionType;
use App\Models\Transaction;
use Exception;
use Illuminate\Console\Command;

class approveInvoice extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'approve:invoice';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $invoices = Transaction::where('type', TransactionType::SHIPPING_INVOICE)->where('status', ApprovalStatus::PENDING_SUBMISSION)->get();

        foreach ($invoices as $invoice) {
            $packingList = $invoice->owner;
            $order = $packingList->owner;

            try {
                (App()->make(ApproveShippingInvoiceTransactionProcessor::class))->execute($packingList);
                $this->info('Invoice Approved for reference ' . $order->reference . '.');
            } catch (Exception $exception) {
                $this->info('Failed to Approve invoice for reference ' . $order->reference . '. Exception: ' . $exception->getMessage());
            }
        }
    }
}
