<?php

namespace App\Modules\Procurement\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Procurement\Exceptions\ReceivingOperationalException;
use App\Modules\Procurement\Models\PurchaseOrder;
use App\Modules\Procurement\Requests\ApprovePurchaseOrderRequest;
use App\Modules\Procurement\Requests\CancelPurchaseOrderRequest;
use App\Modules\Procurement\Services\PurchaseOrderLifecycleService;
use Illuminate\Http\RedirectResponse;

class PurchaseOrderTransitionController extends Controller
{
    public function __construct(
        private readonly PurchaseOrderLifecycleService $lifecycle,
    ) {}

    public function approve(ApprovePurchaseOrderRequest $request, PurchaseOrder $purchaseOrder): RedirectResponse
    {
        $this->authorize('operate', $purchaseOrder);
        $tenantId = (int) $request->user()->tenant_id;

        try {
            $this->lifecycle->approve($tenantId, (int) $purchaseOrder->id);
        } catch (ReceivingOperationalException $e) {
            return redirect()
                ->back()
                ->withErrors(['operational' => $e->getMessage()]);
        }

        return redirect()
            ->route('procurement.purchase-orders.show', $purchaseOrder)
            ->with('status', __('procurement.po.flash.approved'));
    }

    public function cancel(CancelPurchaseOrderRequest $request, PurchaseOrder $purchaseOrder): RedirectResponse
    {
        $this->authorize('operate', $purchaseOrder);
        $tenantId = (int) $request->user()->tenant_id;

        try {
            $this->lifecycle->cancel($tenantId, (int) $purchaseOrder->id);
        } catch (ReceivingOperationalException $e) {
            return redirect()
                ->back()
                ->withErrors(['operational' => $e->getMessage()]);
        }

        return redirect()
            ->route('procurement.purchase-orders.show', $purchaseOrder)
            ->with('status', __('procurement.po.flash.cancelled'));
    }
}
