<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Controller;

use OCA\Mitgliederverwaltung\Service\AuditService;
use OCP\AppFramework\ApiController;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IRequest;
use Psr\Log\LoggerInterface;

/**
 * REST API controller for the audit log.
 *
 * Part of Issue #40.
 */
class AuditController extends ApiController {

    private AuditService $auditService;
    private LoggerInterface $logger;

    public function __construct(
        string $appName,
        IRequest $request,
        AuditService $auditService,
        LoggerInterface $logger
    ) {
        parent::__construct($appName, $request);
        $this->auditService = $auditService;
        $this->logger = $logger;
    }

    /**
     * List audit log entries with optional filters.
     *
     * GET /api/v1/audit-log?entitaet=member&ncUserId=admin&from=2026-01-01&to=2026-12-31&limit=50&offset=0
     */
    #[NoCSRFRequired]
    public function index(): JSONResponse {
        try {
            $entitaet = $this->request->getParam('entitaet');
            $entitaetId = $this->request->getParam('entitaetId');
            $ncUserId = $this->request->getParam('ncUserId');
            $fromDate = $this->request->getParam('from');
            $toDate = $this->request->getParam('to');
            $limit = $this->request->getParam('limit');
            $offset = $this->request->getParam('offset');

            $result = $this->auditService->getLog(
                $entitaet ?: null,
                $entitaetId !== null ? (int)$entitaetId : null,
                $ncUserId ?: null,
                $fromDate ?: null,
                $toDate ?: null,
                $limit !== null ? (int)$limit : 50,
                $offset !== null ? (int)$offset : 0
            );

            return new JSONResponse($result);
        } catch (\Exception $e) {
            $this->logger->error('Failed to query audit log', [
                'exception' => $e,
                'app' => 'mitgliederverwaltung',
            ]);
            return new JSONResponse(
                ['error' => 'Internal server error'],
                Http::STATUS_INTERNAL_SERVER_ERROR
            );
        }
    }
}
