<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpInventorySerialNumbers\Pages;

use App\Business\Inventory\InventorySerialNumberGovernanceService;
use App\Filament\Resources\DberpInventorySerialNumbers\Concerns\InteractsWithInventorySerialNumberGovernanceToggle;
use App\Filament\Resources\DberpInventorySerialNumbers\DberpInventorySerialNumberResource;
use App\Filament\Resources\Pages\EditRecord;
use Illuminate\Database\Eloquent\Model;

class EditDberpInventorySerialNumber extends EditRecord
{
    use InteractsWithInventorySerialNumberGovernanceToggle;

    protected static string $resource = DberpInventorySerialNumberResource::class;

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

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeSave(array $data): array
    {
        $allowed = app(InventorySerialNumberGovernanceService::class)->allowedGovernanceAttributeNames();

        return array_intersect_key($data, array_flip($allowed));
    }

    /**
     * @param  array<string, mixed>  $data
     */
    protected function handleRecordUpdate(Model $record, array $data): Model
    {
        $allowed = app(InventorySerialNumberGovernanceService::class)->allowedGovernanceAttributeNames();

        $record->forceFill(array_intersect_key($data, array_flip($allowed)))->save();

        return $record->refresh();
    }
}
