<?php

declare(strict_types=1);

namespace App\Filament\Resources\DberpSalespersons\Pages;

use App\Filament\Resources\DberpSalespersons\DberpSalespersonResource;
use App\Filament\Resources\Pages\EditRecord;
use App\Filament\Support\DberpDeleteRecordAction;
use App\Models\DberpSalesperson;
use Filament\Actions\DeleteAction;

class EditDberpSalesperson extends EditRecord
{
    protected static string $resource = DberpSalespersonResource::class;

    /**
     * 打开编辑页时，若已关联职员，表单快照与职员主档对齐（职员后补的部门、岗位、电话等会立即显示）。
     *
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeFill(array $data): array
    {
        if (! empty($data['employee_id'])) {
            return DberpSalesperson::syncSnapshotFieldsFromEmployee($data);
        }

        return $data;
    }

    /**
     * @param  array<string, mixed>  $data
     * @return array<string, mixed>
     */
    protected function mutateFormDataBeforeSave(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;
            }
        }

        $record = $this->getRecord();
        $currentEmployeeId = $record instanceof DberpSalesperson && $record->employee_id !== null
            ? (int) $record->employee_id
            : null;

        if (($data['employee_id'] ?? null) !== null) {
            DberpSalesperson::assertEmployeeEligibleForSalespersonLink(
                (int) $data['employee_id'],
                $currentEmployeeId,
            );
            $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,
                (int) $record->getKey(),
            );
        }

        return $data;
    }

    protected function getHeaderActions(): array
    {
        return [
            DberpDeleteRecordAction::configure(DeleteAction::make()),
        ];
    }
}
