<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpSalespersons\Pages;

use App\Filament\Resources\DberpSalespersons\DberpSalespersonResource;
use App\Filament\Resources\Pages\CreateRecord;
use App\Filament\Support\DberpFormSaveSubheading;
use App\Models\DberpSalesperson;
use Illuminate\Contracts\Support\Htmlable;

class CreateDberpSalesperson extends CreateRecord
{
    protected static string $resource = DberpSalespersonResource::class;

    public function getSubheading(): string|Htmlable|null
    {
        return DberpFormSaveSubheading::append((string) __('dberp.ui.organization_list_salesperson_intro'));
    }

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeCreate(array $data): array
    {
        foreach (['employee_id', 'department_id', 'position_id'] as $key) {
            if (array_key_exists($key, $data) && ($data[$key] === '' || $data[$key] === null)) {
                $data[$key] = null;
            }
        }

        if (($data['employee_id'] ?? null) !== null) {
            DberpSalesperson::assertEmployeeEligibleForSalespersonLink(
                (int) $data['employee_id'],
                null,
            );
            $data = DberpSalesperson::syncSnapshotFieldsFromEmployee($data);
        }

        if ((bool) ($data['is_enabled'] ?? true)) {
            DberpSalesperson::assertUniqueActiveEmployeeLink(
                isset($data['employee_id']) && $data['employee_id'] !== null ? (int) $data['employee_id'] : null,
                null,
            );
        }

        return $data;
    }
}
