<?php
declare(strict_types=1);

namespace App\Modules\Settings;

use App\Core\Http\Request;
use App\Core\Http\Response;
use App\Core\I18n\Translator;
use App\Core\Security\Csrf;
use App\Core\Support\Flash;
use App\Core\View\Template;
use App\Core\Http\RedirectPathResolver;
use App\Modules\Auth\AuthService;
use Throwable;

final class ApaczkaIntegrationController
{
    public function __construct(
        private readonly Template $template,
        private readonly Translator $translator,
        private readonly AuthService $auth,
        private readonly ApaczkaIntegrationRepository $repository,
        private readonly ApaczkaApiClient $apiClient
    ) {
    }

    public function index(Request $request): Response
    {
        $settings = $this->repository->getSettings();

        $html = $this->template->render('settings/apaczka', [
            'title' => $this->translator->get('settings.apaczka.title'),
            'activeMenu' => 'settings',
            'activeSettings' => 'apaczka',
            'user' => $this->auth->user(),
            'csrfToken' => Csrf::token(),
            'settings' => $settings,
            'errorMessage' => (string) Flash::get('settings_error', ''),
            'successMessage' => (string) Flash::get('settings_success', ''),
        ], 'layouts/app');

        return Response::html($html);
    }

    public function save(Request $request): Response
    {
        $redirectTo = RedirectPathResolver::resolve((string) $request->input('return_to', '/settings/integrations/apaczka'), ['/settings/integrations'], '/settings/integrations/apaczka');

        if (!Csrf::validate((string) $request->input('_token', ''))) {
            Flash::set('settings_error', $this->translator->get('auth.errors.csrf_expired'));
            return Response::redirect($redirectTo);
        }

        $appId = trim((string) $request->input('app_id', ''));
        if ($appId === '') {
            Flash::set('settings_error', $this->translator->get('settings.apaczka.validation.app_id_required'));
            return Response::redirect($redirectTo);
        }

        try {
            $this->repository->saveSettings([
                'app_id' => $appId,
                'app_secret' => trim((string) $request->input('app_secret', '')),
            ]);
            Flash::set('settings_success', $this->translator->get('settings.apaczka.flash.saved'));
        } catch (Throwable $exception) {
            Flash::set(
                'settings_error',
                $this->translator->get('settings.apaczka.flash.save_failed') . ' ' . $exception->getMessage()
            );
        }

        return Response::redirect($redirectTo);
    }

    public function test(Request $request): Response
    {
        $redirectTo = RedirectPathResolver::resolve((string) $request->input('return_to', '/settings/integrations/apaczka'), ['/settings/integrations'], '/settings/integrations/apaczka');
        if (!Csrf::validate((string) $request->input('_token', ''))) {
            Flash::set('settings_error', $this->translator->get('auth.errors.csrf_expired'));
            return Response::redirect($redirectTo);
        }

        try {
            $services = $this->repository->testConnection($this->apiClient);
            Flash::set('settings_success', $this->translator->get('settings.apaczka.flash.test_success', [
                'count' => (string) count($services),
            ]));
        } catch (Throwable $exception) {
            Flash::set(
                'settings_error',
                $this->translator->get('settings.apaczka.flash.test_failed') . ' ' . $exception->getMessage()
            );
        }

        return Response::redirect($redirectTo);
    }

}
