<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPurchaseInquiries\Pages;

use App\Business\Purchase\PurchaseInquiryGenerationService;
use App\Filament\Resources\DberpPurchaseInquiries\Concerns\ProvidesDberpPurchaseInquiryFromRequestFormFields;
use App\Filament\Resources\DberpPurchaseInquiries\DberpPurchaseInquiryResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Models\DberpPurchaseRequest;
use Filament\Schemas\Schema;
use Filament\Support\Enums\Width;
use Illuminate\Database\Eloquent\Model;

class CreateDberpPurchaseInquiry extends CreateRecord
{
    use ProvidesDberpPurchaseInquiryFromRequestFormFields;

    protected static string $resource = DberpPurchaseInquiryResource::class;

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

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

        $purchaseRequestId = request()->integer('purchase_request_id') ?: null;

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

        $this->form->fill([
            'purchase_request_id' => $purchaseRequestId,
            'inquiry_date' => now()->toDateString(),
            'lines' => $this->buildInquiryLinesFromPurchaseRequest($purchaseRequestId),
            'handler_employee_id' => DberpPurchaseRequest::query()->whereKey($purchaseRequestId)->value('applicant_employee_id'),
            'supplier_ids' => ($supplierId = DberpPurchaseRequest::query()->whereKey($purchaseRequestId)->value('suggested_supplier_id'))
                ? [(int) $supplierId]
                : [],
        ]);
    }

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

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

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

        return parent::getRedirectUrl();
    }

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordCreation(array $data): Model
    {
        $request = DberpPurchaseRequest::query()->findOrFail((int) $data['purchase_request_id']);

        return app(PurchaseInquiryGenerationService::class)->generateFromPurchaseRequest(
            request: $request,
            itemQuantities: $this->extractInquiryLineQuantitiesFromForm($data),
            supplierIds: array_values(array_map(intval(...), (array) ($data['supplier_ids'] ?? []))),
            handlerEmployeeId: ($data['handler_employee_id'] ?? null) ? (int) $data['handler_employee_id'] : null,
            inquiryDate: $data['inquiry_date'] ?? now()->toDateString(),
            remark: $data['remark'] ?? null,
        );
    }
}
