<?php

declare(strict_types=1);

namespace OCA\Mitgliederverwaltung\Controller;

use OCA\Mitgliederverwaltung\Service\InjuryService;
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 injury tracking.
 *
 * Part of Issue #57.
 */
class InjuryController extends ApiController {

    use ApiControllerTrait;

    private InjuryService $injuryService;
    private LoggerInterface $logger;

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

    #[NoCSRFRequired]
    public function index(): JSONResponse {
        return $this->handleAction(function () {
            $memberId = $this->request->getParam('memberId');
            $lagerId = $this->request->getParam('lagerId');

            $injuries = $this->injuryService->findAll(
                $memberId !== null ? (int)$memberId : null,
                $lagerId !== null ? (int)$lagerId : null,
                $this->request->getParam('dateFrom'),
                $this->request->getParam('dateTo')
            );

            return new JSONResponse(['data' => $injuries]);
        }, 'Verletzungen auflisten');
    }

    #[NoCSRFRequired]
    public function show(int $id): JSONResponse {
        return $this->handleAction(function () use ($id) {
            return new JSONResponse($this->injuryService->find($id));
        }, 'Verletzungseintrag');
    }

    public function create(): JSONResponse {
        return $this->handleAction(function () {
            $data = $this->getRequestData();
            $involvedMemberIds = $data['involvedMemberIds'] ?? [];
            unset($data['involvedMemberIds']);

            $injury = $this->injuryService->create($data, $involvedMemberIds);
            return new JSONResponse($injury, Http::STATUS_CREATED);
        }, 'Verletzung erstellen');
    }

    public function update(int $id): JSONResponse {
        return $this->handleAction(function () use ($id) {
            $data = $this->getRequestData();
            $involvedMemberIds = array_key_exists('involvedMemberIds', $data) ? $data['involvedMemberIds'] : null;
            unset($data['involvedMemberIds']);

            return new JSONResponse($this->injuryService->update($id, $data, $involvedMemberIds));
        }, 'Verletzungseintrag');
    }

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

    public function addInvolved(int $id): JSONResponse {
        return $this->handleAction(function () use ($id) {
            $data = $this->getRequestData();
            $memberId = $data['memberId'] ?? null;

            if ($memberId === null) {
                return new JSONResponse(
                    ['error' => 'memberId ist erforderlich'],
                    Http::STATUS_BAD_REQUEST
                );
            }

            $this->injuryService->addInvolvedMember($id, (int)$memberId);
            return new JSONResponse(['status' => 'added'], Http::STATUS_CREATED);
        }, 'Beteiligte Person hinzufuegen');
    }

    public function removeInvolved(int $id, int $memberId): JSONResponse {
        return $this->handleAction(function () use ($id, $memberId) {
            $this->injuryService->removeInvolvedMember($id, $memberId);
            return new JSONResponse(['status' => 'removed']);
        }, 'Beteiligte Person entfernen');
    }
}
