<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPurchaseReturns\Pages;

use App\Business\Purchase\PurchaseReturnReferenceDefaultsResolver;
use App\Filament\Resources\DberpPurchaseReturns\DberpPurchaseReturnResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Models\DberpPurchaseOrder;
use App\Models\DberpPurchaseReceiptOrder;
use Filament\Notifications\Notification;

class CreateDberpPurchaseReturn extends CreateRecord
{
    protected static string $resource = DberpPurchaseReturnResource::class;

    public function mount(): void
    {
        parent::mount();

        $resolver = app(PurchaseReturnReferenceDefaultsResolver::class);
        $receiptId = request()->integer('purchase_receipt_order_id');

        if ($receiptId > 0) {
            $receipt = DberpPurchaseReceiptOrder::query()->find($receiptId);

            if ($receipt instanceof DberpPurchaseReceiptOrder) {
                $this->form->fill(array_merge(
                    ['business_time' => now()],
                    $resolver->resolveFromPurchaseReceipt($receipt),
                ));

                return;
            }
        }

        $purchaseOrderId = request()->integer('purchase_order_id');

        if ($purchaseOrderId <= 0) {
            return;
        }

        $order = DberpPurchaseOrder::query()->with('items')->find($purchaseOrderId);

        if (! $order instanceof DberpPurchaseOrder) {
            return;
        }

        $this->form->fill(array_merge(
            [
                'purchase_order_id' => $order->getKey(),
                'business_time' => now(),
            ],
            $resolver->resolveFromPurchaseOrder($order),
        ));

        if ($resolver->hasAmbiguousWarehouseForPurchaseOrder($order)) {
            Notification::make()
                ->title((string) __('dberp.notifications.warning'))
                ->body((string) __('dberp.messages.purchase_return_ambiguous_warehouse'))
                ->warning()
                ->send();
        }
    }
}
