<?php

declare(strict_types=1);

/**
 * 本文件属于 DBErp 进销存系统。
 *
 * 版权所有 © 2026 北京珑大钜商科技有限公司。保留所有权利。
 *
 * 未经官方授权，不得删除、篡改或隐藏本文件中的版权声明、产品标识与来源信息。
 * 商业授权、官方更新与技术支持服务，请以珑大官方支持中心记录为准。
 *
 * @link https://support.loongdom.cn
 * @see  https://www.dberp.com.cn
 */

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);
    }
}
