<?php

namespace App\Trait;

use App\Models\Client\Client;
use App\Models\Contact\Hub\ContactMessage;
use App\Models\Dsar\Dsar;
use App\Services\HistoryService;

/**
 * Records human actions taken on inbound emails (the /inbox and /inbox/triage
 * screens) into the activity history.
 *
 * Every action is logged against the message itself so each email carries a
 * complete, self-contained audit trail. When the email is matched to a DSAR the
 * same entry is mirrored onto that DSAR and its Client, so it also surfaces on
 * the case timelines staff actually read — matching the both-owners pattern used
 * by outbound sends (DsarService / ResponseLogger).
 */
trait LogsInboxActivity
{
    protected function recordInboxAction(?ContactMessage $message, string $action, array $context = []): void
    {
        if (! $message) {
            return;
        }

        try {
            $history = app(HistoryService::class);

            $context = array_merge([
                'message_id' => $message->id,
                'subject'    => $message->subject,
                'from'       => $message->from_email,
            ], $context);

            // The email's own trail — always written, matched or not.
            $history->add($message, $action, $context);

            // Mirror onto the matched DSAR and its Client for case-timeline visibility.
            $dsar = ($message->messageable_type === Dsar::class && $message->messageable_id)
                ? Dsar::withoutGlobalScopes()->with('claim.client')->find($message->messageable_id)
                : null;

            if ($dsar) {
                $history->add($dsar, $action, array_merge(['dsar_id' => $dsar->id], $context));

                $client = $dsar->claim?->client;
                if ($client) {
                    $history->add($client, $action, $context);
                }
            } elseif ($message->messageable_type === Client::class && $message->messageable_id) {
                // Email linked directly to a client (matched by sender address at
                // ingest, or linked manually from the inbox) — mirror onto the
                // client timeline so the action surfaces on the case the same way
                // it does for DSAR-matched emails.
                $client = Client::find($message->messageable_id);
                if ($client) {
                    $history->add($client, $action, $context);
                }
            }
        } catch (\Throwable $e) {
            report($e);
        }
    }
}
