<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpSalesOutbounds\Pages;

use App\Business\MasterData\DberpDocumentAddressSnapshotService;
use App\Filament\Resources\DberpSalesOutbounds\DberpSalesOutboundResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Models\DberpSalesOrder;
use App\Support\DberpDocumentRemarkPropagation;

class CreateDberpSalesOutbound extends CreateRecord
{
    protected static string $resource = DberpSalesOutboundResource::class;

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

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

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

        $salesOrderId = request()->integer('sales_order_id');

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

        $order = DberpSalesOrder::query()->find($salesOrderId);

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

        $this->form->fill([
            'sales_order_id' => $order->getKey(),
            'customer_id' => $order->customer_id,
            'handler_employee_id' => $order->handler_employee_id,
            'business_time' => now(),
            'remark' => DberpDocumentRemarkPropagation::trimmedOrNull($order->remark),
        ]);
    }
}
