<?php

declare(strict_types=1);

/*
 * This file is part of SolidInvoice project.
 *
 * (c) Pierre du Plessis <open-source@solidworx.co>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace SolidInvoice\InstallBundle\Action;

use SolidInvoice\InstallBundle\Exception\ApplicationInstalledException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

final class Finish extends AbstractController
{
    public function __construct(
        private readonly string $projectDir,
        #[Autowire(env: 'SOLIDINVOICE_RUNTIME')]
        private readonly ?string $runtime = null
    ) {
    }

    public function __invoke(Request $request): Response
    {
        $session = $request->getSession();

        if ($session instanceof SessionInterface && (! $session->has('installation_step') || ! filter_var($session->remove('installation_step'), FILTER_VALIDATE_BOOLEAN))) {
            throw new ApplicationInstalledException();
        }

        $binDir = $this->projectDir . '/bin';

        return $this->render(
            '@SolidInvoiceInstall/finish.html.twig',
            [
                'binDir' => $binDir,
                'runtime' => $this->runtime,
            ]
        );
    }
}
