<?php

namespace App\Livewire\Inventory;

use App\Domain\Inventory\Enums\PurchaseOrderStatus;
use App\Domain\Inventory\Models\PurchaseOrder;
use App\Domain\Inventory\Services\PurchaseOrderService;
use App\Domain\Shared\Exceptions\DomainException;
use App\Domain\Shared\Exceptions\InvalidStatusTransitionException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;

#[Layout('layouts.app')]
#[Title('تفاصيل أمر الشراء')]
class PurchaseOrderShow extends Component
{
    public PurchaseOrder $purchaseOrder;

    public function mount(PurchaseOrder $purchaseOrder): void
    {
        $this->authorize('inventory.list');
        $this->purchaseOrder = $purchaseOrder->load(['items.product', 'warehouse', 'creator']);
    }

    public function submit(): void
    {
        try {
            app(PurchaseOrderService::class)->submit($this->purchaseOrder, auth()->user());
            session()->flash('success', __('تم إرسال أمر الشراء'));
            $this->purchaseOrder->refresh();
        } catch (InvalidStatusTransitionException|DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function confirm(): void
    {
        try {
            app(PurchaseOrderService::class)->confirm($this->purchaseOrder, auth()->user());
            session()->flash('success', __('تم تأكيد أمر الشراء'));
            $this->purchaseOrder->refresh();
        } catch (InvalidStatusTransitionException|DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function render()
    {
        return view('livewire.inventory.purchase-order-show');
    }
}
