<?php

namespace Planaday\Config;

use Planaday\Platform\PlatformAbstraction\LocalizationController;
use Planaday\Platform\PlatformAbstraction\UserService;
use Planaday\Utility\DependencyInjection\Container;
use Planaday\Utility\DependencyInjection\InjectionImpossibleException;
use Planaday\Utility\Endpoints\ApiController;
use Planaday\Utility\Endpoints\RequestMethod;
use Planaday\Utility\Endpoints\ApiEndpoint;
use Planaday\Utility\Endpoints\RequestData;
use Planaday\Utility\FormBuilder\InvalidFormDataException;
use Planaday\Utility\FormBuilder\SubmitStrategies\RestResponses\Message;
use Planaday\Utility\FormBuilder\SubmitStrategies\RestResponses\ResponseStatus;
use Planaday\Utility\FormBuilder\SubmitStrategies\RestResponses\RestResponse;
use Planaday\Utility\PluginData;

#[ApiController(1, 'settings')]
class SettingsPluginApi {
	public function __construct(
		protected Container $componentRegistry,
		protected PluginData $pluginData,
		protected UserService $userService,
		protected LocalizationController $translator
	) {}

	#[ApiEndpoint('/', RequestMethod::POST)]
	public function saveSettings(RequestData $request): RestResponse {
		if (!$this->userService->isAdmin())
			return (new Message())
				->setStatus(ResponseStatus::ConfigError)
				->setMessage('unauthorized: You are not authorized to access this endpoint');

		foreach ($request->getBody() as $key => $value) {
			if (!is_a($key, OptionGroupEnum::class, true)) continue;

			$class = $key::getClassName();

			if (!is_a($class, GlobalSetting::class, true)) continue;
			if (!is_a($class, SettingsWithForm::class, true)) continue;

			try{
				/** @var GlobalSetting&SettingsWithForm $component */
				$component = $this->componentRegistry->getInstance($class);
			} catch (InjectionImpossibleException){
				continue;
			}

			$form = $component->getFormGroup();

			try {
				$form->setValue($value);
			} catch (InvalidFormDataException $e){
				return (new Message())
					->setStatus(ResponseStatus::Failed)
					->setErrors($e->getErrors())
					->setMessage($this->translator->translate('Sommige velden zijn niet correct ingevuld.'));
			}

			$valid = $form->validate();
			if ($valid !== true) {
				return (new Message())
					->setStatus(ResponseStatus::Failed)
					->setErrors([$key => $valid->getErrors()])
					->setMessage($this->translator->translate('Sommige velden zijn niet correct ingevuld.'));
			}

			$component->save();
			return (new Message())
				->setStatus(ResponseStatus::Success)
				->setMessage($this->translator->translate('Instellingen succesvol bijgewerkt'));
		}

		return (new Message())
			->setStatus(ResponseStatus::Failed)
			->setMessage($this->translator->translate("Deze instelling is niet bekend"));
	}
}