<?php

declare(strict_types=1);

namespace MauticPlugin\DealFlowBundle\Controller;

use Mautic\CoreBundle\Controller\CommonController;
use MauticPlugin\DealFlowBundle\Controller\Trait\QueryParamTrait;
use MauticPlugin\DealFlowBundle\Service\DealAuthorization;
use MauticPlugin\DealFlowBundle\Service\UpdateService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

final class UpdateController extends CommonController
{
    use QueryParamTrait;

    public function indexAction(
        Request $request,
        DealAuthorization $authorization,
        UpdateService $updateService,
    ): Response {
        if (!$authorization->canViewSettings()) {
            return $this->accessDenied();
        }

        $forceRefresh = $this->queryFlag($request, 'refresh');
        $updateCheck = $updateService->checkForUpdates($forceRefresh);

        // AJAX request: return JSON instead of full page
        if ($request->isXmlHttpRequest() && $forceRefresh) {
            return new JsonResponse([
                'updateAvailable' => $updateCheck->updateAvailable,
                'latestVersion' => $updateCheck->latestVersion,
                'currentVersion' => $updateCheck->currentVersion,
                'changelog' => $updateCheck->changelog,
                'requiresMigration' => $updateCheck->requiresMigration,
                'eligible' => $updateCheck->eligible,
                'updatesUntil' => $updateCheck->updatesUntil,
                'releasedAt' => $updateCheck->releasedAt,
                'error' => $updateCheck->error,
                'errorMessage' => $updateCheck->errorMessage,
            ]);
        }

        return $this->delegateView([
            'viewParameters' => [
                'updateCheck' => $updateCheck,
            ],
            'contentTemplate' => '@DealFlow/Update/index.html.twig',
            'passthroughVars' => [
                'activeLink' => '#mautic_dealflow_updates',
                'route' => $this->generateUrl('mautic_dealflow_update_check'),
                'mauticContent' => 'dealflow',
            ],
        ]);
    }
}
