<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpPurchaseInquiries\Pages;

use App\Business\Purchase\Enums\PurchaseInquiryStatus;
use App\Filament\Resources\DberpPurchaseInquiries\Concerns\ProvidesDberpPurchaseInquiryCollaborationHeaderActions;
use App\Filament\Resources\DberpPurchaseInquiries\DberpPurchaseInquiryResource;
use App\Models\DberpPurchaseInquiry;
use Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;

class EditDberpPurchaseInquiry extends EditRecord
{
    use ProvidesDberpPurchaseInquiryCollaborationHeaderActions;

    protected static string $resource = DberpPurchaseInquiryResource::class;

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        /** @var DberpPurchaseInquiry $record */
        if ($record->status !== PurchaseInquiryStatus::Open->value) {
            return $record;
        }

        $record->fill([
            'inquiry_date' => $data['inquiry_date'] ?? $record->inquiry_date,
            'handler_employee_id' => $data['handler_employee_id'] ?? null,
            'status' => $data['status'] ?? $record->status,
            'remark' => $data['remark'] ?? null,
        ])->save();

        return $record->refresh();
    }

    protected function getHeaderActions(): array
    {
        return [
            ...$this->purchaseInquiryCollaborationHeaderActions(),
        ];
    }

    protected function getPurchaseInquiryCollaborationRecord(): DberpPurchaseInquiry
    {
        return $this->record;
    }
}
