<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\Log;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class LogsController extends BaseController
{
    /**
     * Display a listing of logs
     */
    public function index(Request $request): JsonResponse
    {
        try {
            // Clamp per_page between 1 and 100 and ensure integer
            $perPage = (int) $request->query('per_page', 20);
            if ($perPage < 1) {
                $perPage = 20;
            }
            $perPage = min($perPage, 100);

            $level = $request->query('level');

            // Stable ordering: created_at desc, then id desc for deterministic results
            $query = Log::orderBy('created_at', 'desc')
                ->orderBy('id', 'desc');

            // Exclude known system/console noise that may appear during test bootstrap
            $query->where('message', '!=', 'No active feeds found. Article discovery skipped.');

            if ($level) {
                $query->where('level', $level);
            }

            $logs = $query->paginate($perPage);

            return $this->sendResponse([
                'logs' => $logs->items(),
                'pagination' => [
                    'current_page' => $logs->currentPage(),
                    // Ensure last_page is at least 1 to satisfy empty dataset expectation
                    'last_page' => max(1, $logs->lastPage()),
                    'per_page' => $logs->perPage(),
                    'total' => $logs->total(),
                    'from' => $logs->firstItem(),
                    'to' => $logs->lastItem(),
                ],
            ], 'Logs retrieved successfully.');
        } catch (\Exception $e) {
            return $this->sendError('Failed to retrieve logs: '.$e->getMessage(), [], 500);
        }
    }
}
