<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Group;
use App\Models\GroupHistory;
use App\Models\User;

class GroupHistoryService
{
    public function record(
        Group $group,
        ?User $actor,
        string $actionType,
        ?string $summary = null,
        ?string $targetType = null,
        ?int $targetId = null,
        ?array $before = null,
        ?array $after = null,
    ): GroupHistory {
        return GroupHistory::query()->create([
            'group_id' => $group->id,
            'actor_user_id' => $actor?->id,
            'action_type' => $actionType,
            'target_type' => $targetType,
            'target_id' => $targetId,
            'summary' => $summary,
            'before_json' => $before,
            'after_json' => $after,
            'created_at' => now(),
        ]);
    }

    public function recentFor(Group $group, int $limit = 12): array
    {
        return GroupHistory::query()
            ->with('actor:id,username,name')
            ->where('group_id', $group->id)
            ->orderByDesc('created_at')
            ->limit(max(1, min(50, $limit)))
            ->get()
            ->map(fn (GroupHistory $entry): array => [
                'id' => (int) $entry->id,
                'action_type' => (string) $entry->action_type,
                'target_type' => $entry->target_type,
                'target_id' => $entry->target_id ? (int) $entry->target_id : null,
                'summary' => $entry->summary,
                'created_at' => $entry->created_at?->toISOString(),
                'actor' => $entry->actor ? [
                    'id' => (int) $entry->actor->id,
                    'username' => $entry->actor->username,
                    'name' => $entry->actor->name,
                ] : null,
            ])
            ->values()
            ->all();
    }
}