<?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\Modules\Auth\AuthService;
use Throwable;

final class FakturowniaIntegrationController
{
    public function __construct(
        private readonly Template $template,
        private readonly Translator $translator,
        private readonly AuthService $auth,
        private readonly FakturowniaIntegrationRepository $repository,
        private readonly FakturowniaApiClient $apiClient,
        private readonly IntegrationsRepository $integrations
    ) {
    }

    public function index(Request $request): Response
    {
        $html = $this->template->render('settings/fakturownia', [
            'title' => 'Integracja Fakturownia',
            'activeMenu' => 'settings',
            'activeSettings' => 'integrations',
            'user' => $this->auth->user(),
            'csrfToken' => Csrf::token(),
            'settings' => $this->repository->getSettings(),
            'flashSave' => (string) Flash::get('fakturownia.save', ''),
            'flashTest' => (string) Flash::get('fakturownia.test', ''),
            'flashError' => (string) Flash::get('fakturownia.error', ''),
        ], 'layouts/app');

        return Response::html($html);
    }

    public function edit(Request $request): Response
    {
        return Response::redirect('/settings/integrations/fakturownia');
    }

    public function save(Request $request): Response
    {
        $redirectTo = '/settings/integrations/fakturownia';

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

        try {
            $this->repository->saveSettings([
                'account_prefix' => (string) $request->input('account_prefix', ''),
                'api_token' => (string) $request->input('api_token', ''),
                'department_id' => (string) $request->input('department_id', ''),
                'default_kind' => (string) $request->input('default_kind', 'vat'),
                'default_payment_to_days' => (int) $request->input('default_payment_to_days', 7),
                'is_active' => $request->input('is_active', ''),
            ]);

            Flash::set('fakturownia.save', 'Zapisano konfiguracje Fakturowni.');
        } catch (Throwable $exception) {
            Flash::set('fakturownia.error', 'Nie udalo sie zapisac konfiguracji: ' . $exception->getMessage());
        }

        return Response::redirect($redirectTo);
    }

    public function test(Request $request): Response
    {
        $redirectTo = '/settings/integrations/fakturownia';

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

        $settings = $this->repository->getSettings();
        $integrationId = (int) ($settings['integration_id'] ?? 0);
        $prefix = (string) ($settings['account_prefix'] ?? '');
        $token = $this->repository->getDecryptedToken($integrationId);

        if ($integrationId <= 0 || $prefix === '' || $token === null || $token === '') {
            Flash::set('fakturownia.test', 'Brak prefiksu lub tokenu - uzupelnij dane i zapisz przed testem.');
            $this->integrations->updateTestResult($integrationId, 'fail', 0, 'Brak prefiksu lub tokenu.');
            return Response::redirect($redirectTo);
        }

        $result = $this->apiClient->testConnection($prefix, $token);
        $status = $result['ok'] ? 'ok' : 'fail';
        $this->integrations->updateTestResult(
            $integrationId,
            $status,
            (int) $result['http_code'],
            (string) $result['message']
        );

        $message = $result['ok']
            ? 'OK (HTTP ' . (int) $result['http_code'] . ')'
            : 'BLAD: ' . $result['message'] . ' (HTTP ' . (int) $result['http_code'] . ')';
        Flash::set('fakturownia.test', $message);

        return Response::redirect($redirectTo);
    }

    public function delete(Request $request): Response
    {
        Flash::set('fakturownia.error', 'Fakturownia ma jedna globalna konfiguracje i nie moze byc usunieta.');

        return Response::redirect('/settings/integrations/fakturownia');
    }
}
