<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Controller;

use OCA\Mitgliederverwaltung\Service\CalendarSyncService;
use OCP\AppFramework\ApiController;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\IRequest;
use OCP\IUserSession;
use Psr\Log\LoggerInterface;

/**
 * REST API controller for calendar sync operations.
 *
 * Provides endpoints to check calendar status, trigger a full sync
 * of member birthdays and Juleica reminders to the Nextcloud CalDAV
 * backend, and enable the Calendar UI app.
 */
class CalendarController extends ApiController {

    use ApiControllerTrait;

    private CalendarSyncService $calendarSyncService;
    private IUserSession $userSession;
    private LoggerInterface $logger;

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

    /**
     * Get calendar sync status.
     *
     * GET /api/v1/calendar/status
     *
     * @return JSONResponse Status information about the calendar setup
     */
    public function status(): JSONResponse {
        return $this->handleAction(function () {
            $userId = $this->userSession->getUser()->getUID();
            $status = $this->calendarSyncService->getCalendarStatus($userId);
            return new JSONResponse($status);
        }, 'Calendar status');
    }

    /**
     * Trigger a full calendar sync to the CalDAV backend.
     *
     * POST /api/v1/calendar/sync
     *
     * Creates the calendar if it doesn't exist, then syncs all member
     * birthdays and Juleica reminders as real CalDAV events.
     *
     * @return JSONResponse Sync statistics (created, updated, deleted, juleica)
     */
    public function sync(): JSONResponse {
        return $this->handleAction(function () {
            $userId = $this->userSession->getUser()->getUID();
            $stats = $this->calendarSyncService->fullSyncCalDav($userId);
            return new JSONResponse($stats);
        }, 'Calendar sync');
    }

    /**
     * Enable the Nextcloud Calendar UI app.
     *
     * POST /api/v1/calendar/enable-app
     *
     * @return JSONResponse Result of the enable operation
     */
    public function enableApp(): JSONResponse {
        return $this->handleAction(function () {
            if ($this->calendarSyncService->isCalendarAppEnabled()) {
                return new JSONResponse(['enabled' => true, 'message' => 'Calendar-App ist bereits aktiviert']);
            }

            $success = $this->calendarSyncService->enableCalendarApp();
            if ($success) {
                return new JSONResponse(['enabled' => true, 'message' => 'Calendar-App wurde aktiviert']);
            }

            return new JSONResponse(
                ['enabled' => false, 'error' => 'Calendar-App konnte nicht aktiviert werden. Bitte installieren Sie die App ueber den Nextcloud App Store.'],
                Http::STATUS_UNPROCESSABLE_ENTITY
            );
        }, 'Enable calendar app');
    }
}
