<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Controller;

use OCA\Mitgliederverwaltung\Service\StufeService;
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 Stufen management.
 *
 * Part of Issue #31.
 */
class StufeController extends ApiController {

    use ApiControllerTrait;

    private StufeService $stufeService;
    private LoggerInterface $logger;

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

    #[NoCSRFRequired]
    public function index(): JSONResponse {
        return $this->handleAction(function () {
            $stufen = $this->stufeService->findAll();
            return new JSONResponse(array_map(fn($s) => $s->jsonSerialize(), $stufen));
        }, 'Stufen auflisten');
    }

    public function create(): JSONResponse {
        return $this->handleAction(function () {
            $stufe = $this->stufeService->create($this->getRequestData());
            return new JSONResponse($stufe, Http::STATUS_CREATED);
        }, 'Stufe erstellen');
    }

    public function update(int $id): JSONResponse {
        return $this->handleAction(function () use ($id) {
            $stufe = $this->stufeService->update($id, $this->getRequestData());
            return new JSONResponse($stufe);
        }, 'Stufe');
    }

    public function destroy(int $id): JSONResponse {
        return $this->handleAction(function () use ($id) {
            $this->stufeService->delete($id);
            return new JSONResponse(['status' => 'deleted']);
        }, 'Stufe');
    }

    /**
     * Get Stufe change suggestions for members exceeding their age range.
     */
    #[NoCSRFRequired]
    public function suggestions(): JSONResponse {
        return $this->handleAction(function () {
            $suggestions = $this->stufeService->getSuggestedChanges();
            return new JSONResponse([
                'data' => $suggestions,
                'count' => count($suggestions),
            ]);
        }, 'Stufe-Vorschlaege');
    }

    #[NoCSRFRequired]
    public function memberHistory(int $memberId): JSONResponse {
        return $this->handleAction(function () use ($memberId) {
            $history = $this->stufeService->getMemberStufeHistory($memberId);
            return new JSONResponse(array_map(fn($h) => $h->jsonSerialize(), $history));
        }, 'Stufe-Verlauf');
    }
}
