<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPurchaseOrders\Pages;

use App\Business\Purchase\PurchaseOrderCreationService;
use App\Filament\Resources\DberpPurchaseOrders\Concerns\ProvidesDberpPurchaseOrderCreationFormFields;
use App\Filament\Resources\DberpPurchaseOrders\DberpPurchaseOrderResource;
use App\Filament\Resources\Pages\CreateRecord;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Illuminate\Database\Eloquent\Model;

class CreateDberpPurchaseOrder extends CreateRecord
{
    use ProvidesDberpPurchaseOrderCreationFormFields;

    protected static string $resource = DberpPurchaseOrderResource::class;

    protected Width|string|null $maxContentWidth = Width::Full;

    public function form(Schema $schema): Schema
    {
        return $schema
            ->columns(1)
            ->components($this->purchaseOrderCreationFormSections());
    }

    protected function getRedirectUrl(): string
    {
        $record = $this->getRecord();
        $resource = static::getResource();

        if ($resource::hasPage('edit') && $resource::canEdit($record)) {
            return $this->getResourceUrl('edit', $this->getRedirectUrlParameters());
        }

        return parent::getRedirectUrl();
    }

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordCreation(array $data): Model
    {
        return app(PurchaseOrderCreationService::class)->createFromFormData($data);
    }
}
