<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpDepartments\Pages;

use App\Filament\Resources\DberpDepartments\DberpDepartmentResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Models\DberpDepartment;
use Illuminate\Validation\ValidationException;

class EditDberpDepartment extends EditRecord
{
    protected static string $resource = DberpDepartmentResource::class;

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeSave(array $data): array
    {
        if (array_key_exists('code', $data) && is_string($data['code']) && trim($data['code']) === '') {
            $data['code'] = null;
        }

        if (array_key_exists('parent_id', $data) && ($data['parent_id'] === '' || $data['parent_id'] === null)) {
            $data['parent_id'] = null;
        }

        $parentId = isset($data['parent_id']) && $data['parent_id'] !== '' && $data['parent_id'] !== null
            ? (int) $data['parent_id']
            : null;

        /** @var DberpDepartment $record */
        $record = $this->getRecord();

        if ($parentId !== null && $parentId === (int) $record->getKey()) {
            throw ValidationException::withMessages([
                'parent_id' => __('dberp.errors.department_parent_invalid'),
            ]);
        }

        if ($parentId !== null && in_array($parentId, $record->getDescendantIds(), true)) {
            throw ValidationException::withMessages([
                'parent_id' => __('dberp.errors.department_parent_is_descendant'),
            ]);
        }

        return $data;
    }
}
