<?php

declare(strict_types=1);

namespace apexl\Io\modules\install\controllers;

use apexl\Config\Configuration as Config;
use apexl\Io\includes\System;
use apexl\Io\modules\install\services\Install;
use Exception;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;

final readonly class installModuleController
{
    public function __construct(private Config $config, private Install $install)
    {
    }

    public function __invoke(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        $body = $request->getParsedBody();

        if (isset($body->install_key) && $body->install_key == $this->config->app->install->key) {
            if (!empty($body->modules)) {
                foreach ($body->modules as $name) {
                    try {
                        $this->install->installModule($name);
                    } catch (Exception $e) {
                        logger('error')->error('Failed to install module {name}: {error}', [
                            'name' => $name,
                            'error' => $e->getMessage(),
                            'exception' => $e,
                        ]);
                    }
                }
            }
        } else {
            return System::asJson($response, [
                'message' => sprintf(
                    'The provided installation key "%s" does not match expected key.',
                    !empty($body->install_key) ? $body->install_key : 'Unknown Key'
                ),
            ], 401);

        }

        return System::asJson($response, ["message" => "Installation Completed."]);
    }

}
