<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPurchaseReceipts\Pages;

use App\Business\MasterData\DberpDocumentAddressSnapshotService;
use App\Business\Purchase\PurchaseOrderRequestedWarehouseResolver;
use App\Filament\Resources\DberpPurchaseReceipts\DberpPurchaseReceiptResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Models\DberpPurchaseOrder;
use App\Support\DberpDocumentRemarkPropagation;
use Filament\Notifications\Notification;

class CreateDberpPurchaseReceipt extends CreateRecord
{
    protected static string $resource = DberpPurchaseReceiptResource::class;

    protected function mutateFormDataBeforeCreate(array $data): array
    {
        $snapshotService = app(DberpDocumentAddressSnapshotService::class);
        $data = $snapshotService->applySupplierSnapshotForPurchaseReceiptCreate($data);

        return $snapshotService->fillWarehouseSnapshot($data);
    }

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

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

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

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

        if ($order === null) {
            return;
        }

        $resolver = app(PurchaseOrderRequestedWarehouseResolver::class);
        $fill = [
            'purchase_order_id' => $order->getKey(),
            'supplier_id' => $order->supplier_id,
            'handler_employee_id' => $order->handler_employee_id,
            'business_time' => now(),
            'arrival_date' => now()->toDateString(),
        ];

        $defaultWarehouseId = $resolver->resolveDefaultReceiptWarehouseId($order);

        if ($defaultWarehouseId !== null) {
            $fill['warehouse_id'] = $defaultWarehouseId;
        }

        $remark = DberpDocumentRemarkPropagation::trimmedOrNull($order->remark);

        if ($remark !== null) {
            $fill['remark'] = $remark;
        }

        $this->form->fill($fill);

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