<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\hooks;

use apexl\Io\includes\Entity;
use apexl\Io\interfaces\AbstractHook;
use apexl\Io\modules\user\services\CurrentUserFactory;

final readonly class AddCreatedByToEntitiesOnSave implements AbstractHook
{
    public function __construct(
        private CurrentUserFactory $currentUserFactory,
    ) {}

    public function hooks(): array
    {
        return [Entity::HOOK__BEFORE_FIRST_STORE];
    }

    /**
     * First-write-wins: an explicit `created_by` set by the caller is provenance
     * and must survive. `array_key_exists`, not `isset` — a deliberate null means
     * "no human actor" and is a value, not an absence.
     */
    public function __invoke(array $data, Entity $entity): array
    {
        if ($entity->isDataField('created_by') && !array_key_exists('created_by', $data)) {
            $data['created_by'] = $this->currentUserFactory->get()?->id ?? 0;
        }

        return $data;
    }
}
