<?php

declare(strict_types=1);

namespace Apexl\Io\User\Hooks;

use Apexl\Io\Entity;
use Apexl\Io\Interfaces\AbstractHook;
use Apexl\Io\User\Interfaces\StampedActorResolverInterface;

final readonly class AddModifiedByToEntitiesOnSave implements AbstractHook
{
    public function __construct(
        private StampedActorResolverInterface $stampedActorResolver,
    ) {}

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

    /**
     * Last-write-wins, unlike `created_by`: `modified_by` is who saved the row this
     * time, so a value the caller supplied is not provenance to preserve.
     */
    public function __invoke(array $data, Entity $entity): array
    {
        if ($entity->isDataField('modified_by')) {
            $data['modified_by'] = $this->stampedActorResolver->id();
        }

        return $data;
    }
}
