<?php

declare(strict_types=1);

namespace Install\Services;

final class FinalizationService
{
    public function finalize(
        array $config,
        array $database,
        array $environment,
        array $administrator,
        array $migrationSummary
    ): array {
        $storage = PROJECT_PATH . DIRECTORY_SEPARATOR . 'storage';
        $installDirectory = $storage . DIRECTORY_SEPARATOR . 'install';

        if (!is_dir($installDirectory)) {
            if (!mkdir($installDirectory, 0775, true) && !is_dir($installDirectory)) {
                throw new \RuntimeException(
                    'Impossible de créer le dossier storage/install.'
                );
            }
        }

        $installedAt = date('Y-m-d H:i:s');

        $data = [
            'application' => (string)($environment['app_name'] ?? $config['application'] ?? 'Darlink ERP'),
            'edition' => (string)($config['edition'] ?? 'Phoenix'),
            'version' => (string)($config['version'] ?? ''),
            'build' => (string)($config['wizard_build'] ?? 'P2.4.1'),
            'installed_at' => $installedAt,
            'app_url' => (string)($environment['app_url'] ?? ''),
            'database' => [
                'host' => (string)($database['db_host'] ?? ''),
                'port' => (int)($database['db_port'] ?? 3306),
                'name' => (string)($database['db_database'] ?? ''),
                'product' => (string)($database['server_product'] ?? ''),
                'version' => (string)($database['server_version'] ?? ''),
            ],
            'administrator' => [
                'id' => (int)($administrator['user_id'] ?? 0),
                'name' => trim(
                    (string)($administrator['prenom'] ?? '')
                    . ' '
                    . (string)($administrator['nom'] ?? '')
                ),
                'login' => (string)($administrator['login'] ?? ''),
                'email' => (string)($administrator['email'] ?? ''),
                'role' => (string)($administrator['role'] ?? 'ADMINISTRATEUR'),
            ],
            'migrations' => [
                'successes' => (int)($migrationSummary['successes'] ?? 0),
                'failures' => (int)($migrationSummary['failures'] ?? 0),
                'statements' => (int)($migrationSummary['statements'] ?? 0),
                'duration_ms' => (int)($migrationSummary['duration_ms'] ?? 0),
            ],
            'php_version' => PHP_VERSION,
        ];

        $jsonPath = $installDirectory . DIRECTORY_SEPARATOR . 'installation-report.json';
        $htmlPath = $installDirectory . DIRECTORY_SEPARATOR . 'installation-report.html';
        $lockPath = $storage . DIRECTORY_SEPARATOR . 'install.lock';

        file_put_contents(
            $jsonPath,
            json_encode(
                $data,
                JSON_PRETTY_PRINT
                | JSON_UNESCAPED_UNICODE
                | JSON_UNESCAPED_SLASHES
                | JSON_THROW_ON_ERROR
            ),
            LOCK_EX
        );

        $e = static fn (mixed $value): string =>
            htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');

        $html = '<!doctype html><html lang="fr"><head><meta charset="utf-8">'
            . '<title>Rapport d’installation Darlink ERP</title>'
            . '<style>body{font-family:Arial;background:#f5f7fb;color:#1e293b;padding:30px}'
            . '.card{max-width:850px;margin:auto;background:#fff;padding:28px;border-radius:18px}'
            . 'h1{color:#0f4c81}table{width:100%;border-collapse:collapse}'
            . 'td{padding:10px;border-bottom:1px solid #e2e8f0}'
            . 'td:first-child{font-weight:bold;width:38%}</style></head><body><div class="card">'
            . '<h1>' . $e($data['application']) . '</h1>'
            . '<p>Installation réussie le ' . $e($installedAt) . '.</p>'
            . '<table>'
            . '<tr><td>Version</td><td>' . $e($data['version']) . '</td></tr>'
            . '<tr><td>Build</td><td>' . $e($data['build']) . '</td></tr>'
            . '<tr><td>Administrateur</td><td>' . $e($data['administrator']['name']) . '</td></tr>'
            . '<tr><td>Identifiant</td><td>' . $e($data['administrator']['login']) . '</td></tr>'
            . '<tr><td>Base</td><td>' . $e($data['database']['name']) . '</td></tr>'
            . '<tr><td>Migrations réussies</td><td>' . $e($data['migrations']['successes']) . '</td></tr>'
            . '<tr><td>Instructions SQL</td><td>' . $e($data['migrations']['statements']) . '</td></tr>'
            . '<tr><td>PHP</td><td>' . $e($data['php_version']) . '</td></tr>'
            . '</table></div></body></html>';

        file_put_contents($htmlPath, $html, LOCK_EX);

        file_put_contents(
            $lockPath,
            json_encode(
                [
                    'version' => $data['version'],
                    'build' => $data['build'],
                    'installed_at' => $installedAt,
                    'administrator_id' => $data['administrator']['id'],
                ],
                JSON_PRETTY_PRINT
                | JSON_UNESCAPED_UNICODE
                | JSON_THROW_ON_ERROR
            ),
            LOCK_EX
        );

        if (!is_file($lockPath)) {
            throw new \RuntimeException(
                'Le fichier install.lock n’a pas pu être créé.'
            );
        }

        return [
            'success' => true,
            'installed_at' => $installedAt,
            'app_url' => $data['app_url'],
            'administrator' => $data['administrator'],
            'migrations' => $data['migrations'],
            'version' => $data['version'],
            'build' => $data['build'],
        ];
    }
}
