<?php

namespace App\Services;

use App\Interface\HistoryOwner;
use App\Models\Claim\Claim;
use App\Models\User\User;

class HistoryService {
    /**
     * Record a single audit history entry against one owner.
     * The acting user and timestamp are captured automatically.
     */
    public function add(HistoryOwner $historyOwner, string $event, array $context = [], ?int $user = null) {
        $historyOwner->history()->create([
            'action' => $event,
            'user_id' => is_null($user) ? auth()->id() : $user,
            'context' => $context
        ]);
    }

    /**
     * Record a claim-scoped action against BOTH the claim and its client, so the
     * event appears on the claim's own History tab and on the unified client timeline.
     * A claim_id is always merged into the context so the entry can be traced to the claim.
     */
    public function addForClaim(Claim $claim, string $event, array $context = [], ?int $user = null) {
        $context = array_merge(['claim_id' => $claim->id], $context);

        $this->add($claim, $event, $context, $user);

        if ($claim->client) {
            $this->add($claim->client, $event, $context, $user);
        }
    }

    /**
     * Record a system/configuration/security action against the acting user, for
     * entities that are not themselves history owners (statuses, types, settings, etc.).
     */
    public function addForActor(string $event, array $context = [], ?int $user = null) {
        // Prefer the already-authenticated user object; only query when an
        // explicit user id is supplied that differs from the current user.
        $actor = is_null($user) || $user === auth()->id()
            ? auth()->user()
            : User::withoutGlobalScopes()->find($user);

        if ($actor) {
            $this->add($actor, $event, $context, $user);
        }
    }
}
