<?php
declare(strict_types=1);

namespace App\Modules\Settings;

use App\Core\Exceptions\IntegrationConfigException;
use App\Core\Http\RedirectPathResolver;
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\Modules\Auth\AuthService;
use Throwable;

final class PolkurierIntegrationController
{
    public function __construct(
        private readonly Template $template,
        private readonly Translator $translator,
        private readonly AuthService $auth,
        private readonly PolkurierIntegrationRepository $repository,
        private readonly PolkurierApiClient $apiClient,
        private readonly IntegrationsRepository $integrations
    ) {
    }

    public function index(Request $request): Response
    {
        $html = $this->template->render('settings/polkurier', [
            'title' => $this->translator->get('settings.polkurier.title'),
            'activeMenu' => 'settings',
            'activeSettings' => 'integrations',
            'user' => $this->auth->user(),
            'csrfToken' => Csrf::token(),
            'settings' => $this->repository->getSettings(),
            'errorMessage' => (string) Flash::get('settings_error', ''),
            'successMessage' => (string) Flash::get('settings_success', ''),
            'testMessage' => (string) Flash::get('polkurier_test', ''),
        ], 'layouts/app');

        return Response::html($html);
    }

    public function save(Request $request): Response
    {
        $redirectTo = $this->resolveRedirect($request);

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

        try {
            $this->repository->saveSettings([
                'login' => (string) $request->input('login', ''),
                'api_token' => (string) $request->input('api_token', ''),
                'default_label_format' => (string) $request->input('default_label_format', 'PDF'),
                'is_active' => $request->input('is_active', ''),
            ]);
            Flash::set('settings_success', $this->translator->get('settings.polkurier.flash.saved'));
        } catch (Throwable $exception) {
            Flash::set(
                'settings_error',
                $this->translator->get('settings.polkurier.flash.save_failed') . ' ' . $exception->getMessage()
            );
        }

        return Response::redirect($redirectTo);
    }

    public function test(Request $request): Response
    {
        $redirectTo = $this->resolveRedirect($request);

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

        try {
            $credentials = $this->repository->getCredentials();
            if ($credentials === null) {
                throw new IntegrationConfigException('Najpierw zapisz kompletna konfiguracje polkurier (login + Token API + aktywacja).');
            }

            $result = $this->apiClient->testConnection(
                $credentials['login'],
                $credentials['api_token']
            );

            $status = $result['ok'] ? 'ok' : 'fail';
            $this->integrations->updateTestResult(
                $credentials['integration_id'],
                $status,
                (int) $result['http_code'],
                (string) $result['message']
            );

            if ($result['ok']) {
                Flash::set('polkurier_test', $this->translator->get('settings.polkurier.flash.test_success', [
                    'message' => (string) $result['message'],
                ]));
            } else {
                Flash::set('settings_error', $this->translator->get('settings.polkurier.flash.test_failed') . ' ' . $result['message']);
            }
        } catch (Throwable $exception) {
            Flash::set('settings_error', $this->translator->get('settings.polkurier.flash.test_failed') . ' ' . $exception->getMessage());
        }

        return Response::redirect($redirectTo);
    }

    private function resolveRedirect(Request $request): string
    {
        return RedirectPathResolver::resolve(
            (string) $request->input('return_to', '/settings/integrations/polkurier'),
            ['/settings/integrations'],
            '/settings/integrations/polkurier'
        );
    }
}
