<?php

namespace App\Services\Users;

use App\Models\LoginActivity;

class LoginActivityService
{
    public function list(int $perPage, int $page): array
    {
        $perPage = max(1, min($perPage, 200));
        $page = max(1, $page);

        $total = (int) LoginActivity::query()->count();
        $pageCount = (int) max(1, ceil($total / $perPage));

        $activities = LoginActivity::query()
            ->orderByDesc('login_time')
            ->forPage($page, $perPage)
            ->get();

        $normalized = $activities->map(static function (LoginActivity $activity) {
            return [
                'user_id' => $activity->user_id,
                'email' => $activity->email,
                'login_time' => optional($activity->login_time)->toDateTimeString(),
                'logout_time' => optional($activity->logout_time)->toDateTimeString(),
                'ip_address' => $activity->ip_address,
                'user_agent' => $activity->user_agent,
            ];
        })->all();

        return [
            'activities' => $normalized,
            'pagination' => [
                'total' => $total,
                'perPage' => $perPage,
                'currentPage' => $page,
                'pageCount' => $pageCount,
                'hasNext' => $page < $pageCount,
                'hasPrevious' => $page > 1,
            ],
        ];
    }
}
