<?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;

final class IntegrationsHubController
{
    public function __construct(
        private readonly Template $template,
        private readonly Translator $translator,
        private readonly AuthService $auth,
        private readonly IntegrationsRepository $integrations,
        private readonly AllegroIntegrationRepository $allegro,
        private readonly ApaczkaIntegrationRepository $apaczka,
        private readonly InpostIntegrationRepository $inpost,
        private readonly ShopproIntegrationsRepository $shoppro
    ) {
    }

    public function index(Request $request): Response
    {
        $rows = [
            $this->buildAllegroRow('sandbox'),
            $this->buildAllegroRow('production'),
            $this->buildApaczkaRow(),
            $this->buildInpostRow(),
            $this->buildShopproRow(),
        ];

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

        return Response::html($html);
    }

    /**
     * @return array<string, mixed>
     */
    private function buildAllegroRow(string $environment): array
    {
        $env = $environment === 'production' ? 'production' : 'sandbox';
        $settings = $this->allegro->getSettings($env);
        $integrationName = $env === 'production' ? 'Allegro Production' : 'Allegro Sandbox';
        $meta = $this->integrations->findByTypeAndName('allegro', $integrationName) ?? [];

        return [
            'provider' => $this->translator->get('settings.integrations_hub.providers.allegro'),
            'instance' => $this->translator->get('settings.integrations_hub.providers.' . ($env === 'production' ? 'allegro_production' : 'allegro_sandbox')),
            'authorization_status' => !empty($settings['is_connected'])
                ? $this->translator->get('settings.integrations_hub.status.connected')
                : $this->translator->get('settings.integrations_hub.status.not_connected'),
            'secret_status' => !empty($settings['has_client_secret'])
                ? $this->translator->get('settings.integrations_hub.status.saved')
                : $this->translator->get('settings.integrations_hub.status.missing'),
            'is_active' => (int) ($meta['is_active'] ?? 0) === 1,
            'last_test_at' => trim((string) ($meta['last_test_at'] ?? '')),
            'configure_url' => '/settings/integrations/allegro?env=' . rawurlencode($env),
            'configure_label' => $this->translator->get('settings.integrations_hub.actions.configure'),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function buildApaczkaRow(): array
    {
        $settings = $this->apaczka->getSettings();
        $meta = $this->integrations->findByTypeAndName('apaczka', 'Apaczka') ?? [];
        $isConfigured = !empty($settings['has_app_id']) && !empty($settings['has_app_secret']);

        return [
            'provider' => $this->translator->get('settings.integrations_hub.providers.apaczka'),
            'instance' => 'Apaczka',
            'authorization_status' => $isConfigured
                ? $this->translator->get('settings.integrations_hub.status.configured')
                : $this->translator->get('settings.integrations_hub.status.not_configured'),
            'secret_status' => $isConfigured
                ? $this->translator->get('settings.integrations_hub.status.saved')
                : $this->translator->get('settings.integrations_hub.status.missing'),
            'is_active' => (int) ($meta['is_active'] ?? 0) === 1,
            'last_test_at' => trim((string) ($meta['last_test_at'] ?? '')),
            'configure_url' => '/settings/integrations/apaczka',
            'configure_label' => $this->translator->get('settings.integrations_hub.actions.configure'),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function buildInpostRow(): array
    {
        $settings = $this->inpost->getSettings();
        $meta = $this->integrations->findByTypeAndName('inpost', 'InPost ShipX') ?? [];

        return [
            'provider' => $this->translator->get('settings.integrations_hub.providers.inpost'),
            'instance' => 'InPost ShipX',
            'authorization_status' => !empty($settings['has_api_token'])
                ? $this->translator->get('settings.integrations_hub.status.configured')
                : $this->translator->get('settings.integrations_hub.status.not_configured'),
            'secret_status' => !empty($settings['has_api_token'])
                ? $this->translator->get('settings.integrations_hub.status.saved')
                : $this->translator->get('settings.integrations_hub.status.missing'),
            'is_active' => (int) ($meta['is_active'] ?? 0) === 1,
            'last_test_at' => trim((string) ($meta['last_test_at'] ?? '')),
            'configure_url' => '/settings/integrations/inpost',
            'configure_label' => $this->translator->get('settings.integrations_hub.actions.configure'),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function buildShopproRow(): array
    {
        $rows = $this->shoppro->listIntegrations();
        $instancesCount = count($rows);
        $activeCount = 0;
        $configuredCount = 0;
        $lastTestAt = '';

        foreach ($rows as $row) {
            if (!empty($row['is_active'])) {
                $activeCount++;
            }
            if (!empty($row['has_api_key'])) {
                $configuredCount++;
            }

            $testedAt = trim((string) ($row['last_test_at'] ?? ''));
            if ($testedAt !== '' && ($lastTestAt === '' || strcmp($testedAt, $lastTestAt) > 0)) {
                $lastTestAt = $testedAt;
            }
        }

        return [
            'provider' => $this->translator->get('settings.integrations_hub.providers.shoppro'),
            'instance' => $this->translator->get('settings.integrations_hub.providers.shoppro_instances', [
                'count' => $instancesCount,
            ]),
            'authorization_status' => $configuredCount > 0
                ? $this->translator->get('settings.integrations_hub.status.configured')
                : $this->translator->get('settings.integrations_hub.status.not_configured'),
            'secret_status' => $configuredCount > 0
                ? $this->translator->get('settings.integrations_hub.status.saved')
                : $this->translator->get('settings.integrations_hub.status.missing'),
            'is_active' => $activeCount > 0,
            'last_test_at' => $lastTestAt,
            'configure_url' => '/settings/integrations/shoppro',
            'configure_label' => $this->translator->get('settings.integrations_hub.actions.configure'),
        ];
    }

}
