<?php

declare(strict_types=1);

namespace App\Http\Controllers\Api\V1\Account;

use App\Enums\AuthEventType;
use App\Models\AuthEvent;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

/**
 * The user's own recent security activity.
 *
 * Only events that help someone spot a takeover are surfaced, and only their
 * own. Internal risk scores and fraud flags are not included -- section 28
 * keeps those out of user-facing responses.
 */
final class SecurityActivityController extends Controller
{
    /** @var list<AuthEventType> */
    private const VISIBLE_EVENTS = [
        AuthEventType::LoginSuccess,
        AuthEventType::LoginFailed,
        AuthEventType::Logout,
        AuthEventType::PasswordChanged,
        AuthEventType::PasswordResetRequested,
        AuthEventType::EmailVerified,
        AuthEventType::TwoFactorEnabled,
        AuthEventType::TwoFactorDisabled,
        AuthEventType::TokenCreated,
        AuthEventType::TokenRevoked,
        AuthEventType::SuspiciousLogin,
    ];

    public function index(Request $request): JsonResponse
    {
        $events = AuthEvent::query()
            ->where('user_id', $request->user()->getKey())
            ->whereIn('event', array_map(fn (AuthEventType $e): string => $e->value, self::VISIBLE_EVENTS))
            ->latest('created_at')
            ->paginate(perPage: min(50, (int) $request->integer('per_page', 20)));

        return response()->json([
            'data' => collect($events->items())->map(fn (AuthEvent $event): array => [
                'event' => $event->event->value,
                'ip_address' => $event->ip_address,
                'country_code' => $event->country_code,
                // The raw user agent, not the fingerprint hash: the hash is an
                // internal correlation key and means nothing to the user.
                'user_agent' => $event->user_agent,
                'occurred_at' => $event->created_at?->toIso8601String(),
            ]),
            'meta' => [
                'current_page' => $events->currentPage(),
                'last_page' => $events->lastPage(),
                'per_page' => $events->perPage(),
                'total' => $events->total(),
            ],
        ]);
    }
}
