<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\AuditService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AuditLogController extends Controller
{
    public function __construct(
        private readonly AuditService $auditService
    ) {}

    /**
     * List audit log entries with optional filters.
     *
     * Query parameters (all optional):
     *   action       — filter by action constant
     *   actor_type   — admin | portal_user | system | public
     *   actor_email  — filter by actor email
     *   record_type  — filter by affected model name
     *   record_id    — filter by affected record ID
     *   status       — SUCCESS | FAILED
     *   date_from    — Y-m-d inclusive
     *   date_to      — Y-m-d inclusive
     *   per_page     — items per page (10–100, default 50)
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $perPage = (int) $request->input('per_page', 50);
            $perPage = min(max($perPage, 10), 100);

            $filters = $request->only([
                'action',
                'actor_type',
                'actor_email',
                'record_type',
                'record_id',
                'status',
                'date_from',
                'date_to',
            ]);

            $paginator = $this->auditService->list($filters, $perPage);

            return response()->json([
                'success' => true,
                'data'    => $paginator,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch audit logs.',
            ], 500);
        }
    }
}
