<?php

namespace App\Support;

use App\Agent\Workspace;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;

/**
 * Who did this, in a form that survives in the audit log.
 *
 * Everyone here can reach everything, which is the right call for an internal
 * tool, but it only works if every change carries a name. The audit columns
 * existed and were filled with "agent" and "chat", which record the channel and
 * answer nothing when someone asks who changed a budget.
 *
 * A string rather than a foreign key on purpose: the identity has to survive
 * the user row being deleted, and it is read far more often than it is queried.
 * If we ever need "everything Kaushal changed" as a real query, that is the
 * point to add the key, not before.
 */
class Actor
{
    public function __construct(private readonly Workspace $workspace) {}

    /**
     * The person behind the current action, and how they reached it.
     *
     * Falls back to the conversation's owner when there is no session, which is
     * how a queued job still attributes to a person rather than to nobody.
     */
    public function describe(string $channel = 'chat'): string
    {
        $user = Auth::user() ?? $this->workspace->owner();

        return $user
            ? sprintf('%s via %s', $this->name($user), $channel)
            : sprintf('system via %s', $channel);
    }

    private function name(Model $user): string
    {
        $label = $user->getAttribute('email')
            ?: $user->getAttribute('name')
            ?: 'user';

        return sprintf('%s#%s %s', class_basename($user), $user->getKey(), $label);
    }
}
