<?php

namespace App\Controllers\Audit;

use App\Controllers\BaseController;
use App\Services\AuditLogService;
use App\Traits\ResponseTrait;
use CodeIgniter\HTTP\ResponseInterface;
use InvalidArgumentException;

class AuditLogController extends BaseController
{
    use ResponseTrait;

    private AuditLogService $auditLogService;

    public function __construct()
    {
        $this->auditLogService = new AuditLogService();
    }

    public function index(): ResponseInterface
    {
        $filters = [
            'table' => $this->request->getGet('table'),
            'rec_id' => $this->request->getGet('rec_id') ?? $this->request->getGet('recId'),
            'event_id' => $this->request->getGet('event_id') ?? $this->request->getGet('eventId'),
            'activity_id' => $this->request->getGet('activity_id') ?? $this->request->getGet('activityId'),
            'from' => $this->request->getGet('from'),
            'to' => $this->request->getGet('to'),
            'search' => $this->request->getGet('search'),
            'page' => $this->request->getGet('page'),
            'perPage' => $this->request->getGet('perPage') ?? $this->request->getGet('per_page'),
        ];

        try {
            $payload = $this->auditLogService->fetchLogs($filters);

            return $this->respond([
                'status' => 'success',
                'message' => 'Audit logs retrieved successfully',
                'data' => $payload,
            ], 200);

        } catch (InvalidArgumentException $e) {
            return $this->respond([
                'status' => 'failed',
                'message' => $e->getMessage(),
                'data' => null,
            ], 400);
        } catch (\Throwable $e) {
            log_message('error', 'AuditLogController::index error: ' . $e->getMessage());
            return $this->respond([
                'status' => 'failed',
                'message' => 'Unable to retrieve audit logs',
                'data' => null,
            ], 500);
        }
    }
}
