<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Controller;

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

/**
 * REST API controller for membership milestones (Jubilaeen).
 *
 * Part of Issue #59.
 */
class MilestoneController extends ApiController {

    use ApiControllerTrait;

    private MilestoneService $milestoneService;
    private PermissionService $permissionService;
    private IUserSession $userSession;
    private LoggerInterface $logger;

    public function __construct(
        string $appName,
        IRequest $request,
        MilestoneService $milestoneService,
        PermissionService $permissionService,
        IUserSession $userSession,
        LoggerInterface $logger
    ) {
        parent::__construct($appName, $request);
        $this->milestoneService = $milestoneService;
        $this->permissionService = $permissionService;
        $this->userSession = $userSession;
        $this->logger = $logger;
    }

    #[NoCSRFRequired]
    public function index(): JSONResponse {
        return $this->handleAction(function () {
            $year = $this->request->getParam('year');
            $year = $year === null ? (int)(new \DateTime())->format('Y') : (int)$year;
            $includeInactive = $this->request->getParam('includeInactive') === 'true';

            $milestones = $this->milestoneService->getUpcomingMilestones($year, $includeInactive);

            return new JSONResponse([
                'data' => $milestones,
                'year' => $year,
                'count' => count($milestones),
            ]);
        }, 'Meilensteine');
    }

    #[NoCSRFRequired]
    public function getSettings(): JSONResponse {
        return new JSONResponse([
            'thresholds' => $this->milestoneService->getThresholds(),
        ]);
    }

    public function updateSettings(): JSONResponse {
        return $this->handleAction(function () {
            $userId = $this->getCurrentUserId();
            if (!$this->permissionService->isAdmin($userId)) {
                return new JSONResponse(
                    ['error' => 'Nur Administratoren koennen Einstellungen aendern'],
                    Http::STATUS_FORBIDDEN
                );
            }

            $data = $this->getRequestData();
            $thresholds = $data['thresholds'] ?? [];

            if (!is_array($thresholds)) {
                return new JSONResponse(
                    ['error' => 'thresholds muss ein Array von Zahlen sein'],
                    Http::STATUS_BAD_REQUEST
                );
            }

            $this->milestoneService->setThresholds($thresholds);

            return new JSONResponse([
                'thresholds' => $this->milestoneService->getThresholds(),
            ]);
        }, 'Meilenstein-Einstellungen');
    }

    private function getCurrentUserId(): string {
        $user = $this->userSession->getUser();
        return $user ? $user->getUID() : 'system';
    }
}
