<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpSalesReturns\Pages;

use App\Business\Sales\SalesReturnReferenceDefaultsResolver;
use App\Filament\Resources\DberpSalesReturns\DberpSalesReturnResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Models\DberpSalesOrder;
use App\Models\DberpSalesOutboundOrder;

class CreateDberpSalesReturn extends CreateRecord
{
    protected static string $resource = DberpSalesReturnResource::class;

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

        $resolver = app(SalesReturnReferenceDefaultsResolver::class);
        $outboundId = request()->integer('sales_outbound_order_id');

        if ($outboundId > 0) {
            $outbound = DberpSalesOutboundOrder::query()->find($outboundId);

            if ($outbound instanceof DberpSalesOutboundOrder) {
                $this->form->fill(array_merge(
                    ['business_time' => now()],
                    $resolver->resolveFromSalesOutbound($outbound),
                ));

                return;
            }
        }

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

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

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

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

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